dantey89
dantey89

Reputation: 2287

How to use promises with timeouts in a for loop?

I have few functions which should be executed one by one in loop and with delay. Here is the code I have:

function func1() {
  for (var i = 0; i < 3; i++) {
    func2().then(); // await in loop until func2() completed       
  }
}

function func2() {
  return new Promise(succes) {
    for (var i = 0; i < 10; i++) {
      function3().then(); //wait untill function3 and then continue looping
    }
    success();
  }
}

function function3() {
  return new Promise(function(ready) {
    setTimeout(function() {
      // do some stuff
      ready();
    }, 2000);
  });
}

But it doesn't work. What I should change?

Upvotes: 2

Views: 2032

Answers (3)

nem035
nem035

Reputation: 35491

I think what you intended to use is ES8's (ES2017) async/await construct:

async function func1() {
  for (var i = 0; i < 3; i++) {
    console.log(`func1 waiting for func2 #${i + 1}`);
    await func2(); // await in loop until func2() completed 
    console.log(`Finished iteration ${i} for func1`);
  }
}

async function func2() {
  console.log('Started func2');
  for (var i = 0; i < 10; i++) {
    console.log(`func2 waiting for func3 #${i + 1}`);
    await function3(); //wait untill function3 and then continue looping
  }
}

function function3() {
  return new Promise(resolve => setTimeout(resolve, 1000));
}

func1().then(() => console.log('finished'));

For a wider browser support, you can use Babel

.

Upvotes: 4

Piotr Białek
Piotr Białek

Reputation: 2709

I don't know it's a the best solution, but it is some way and i think this easy to implement.

function func1(i){
     i++;
     return new Promise(function(ready){
            setTimeout(function(){  
                func2(i);
                ready(i);           
            }, 1000); 
    });
}

function func2(i = 0){
  if(i < 10){
    func1(i).then((test) => {
      console.log(test);
    })
  } else {
    return false;
  }
}
func2();

Upvotes: 0

Vortic
Vortic

Reputation: 75

You can use jQuery's .each() , it's synchronous so the next loop won't fire until the previous ends. You can also add callbacks but they are not really needed here.

Upvotes: -1

Related Questions