Skip to content Skip to sidebar Skip to footer

Wait In For Loops For Async Function

I need run startFunc function synchronously and 'wait' in for loop to finish task, to run it again. I can't use await in startFunc(). I need something like .wait() in c# I except r

Solution 1:

You need to put the for loop in an async function as well, so you can await each call to startFunc:

functioncallToDB(ms) {
  returnnewPromise(resolve =>setTimeout(resolve, ms));
}
asyncfunctionstartFunc (i) {
  console.log('start', i);
  awaitcallToDB(1000);
  console.log('end', i);
}

(async () => {
  for (let i = 0; i < 5; i++) {
    awaitstartFunc(i);
  }
})();

Another method would be to continually chain .thens:

functioncallToDB(ms) {
  returnnewPromise(resolve =>setTimeout(resolve, ms));
}
asyncfunctionstartFunc (i) {
  console.log('start', i);
  awaitcallToDB(1000);
  console.log('end', i);
}

let prom = Promise.resolve();
for (let i = 0; i < 5; i++) {
  prom = prom.then(() =>startFunc(i));
}

Or you could use .reduce and continually pass along the last Promise as the accumulator, rather than assign to an outside variable:

functioncallToDB(ms) {
  returnnewPromise(resolve =>setTimeout(resolve, ms));
}
asyncfunctionstartFunc (i) {
  console.log('start', i);
  awaitcallToDB(1000);
  console.log('end', i);
}

const finalProm = Array.from({ length: 5 })
  .reduce(
    (lastProm, _, i) => lastProm.then(() =>startFunc(i)),
    Promise.resolve()
  );

Post a Comment for "Wait In For Loops For Async Function"