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 result: start 1 end 1 start 2 end 2 etc...

function callToDB(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function startFunc (i) {
  console.log('start', i);
  await callToDB(1000);
  console.log('end', i);
}

for (let i = 0; i < 5; i++) {
  startFunc(i);
}

Answers:

Answer

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

function callToDB(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function startFunc (i) {
  console.log('start', i);
  await callToDB(1000);
  console.log('end', i);
}

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

Another method would be to continually chain .thens:

function callToDB(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function startFunc (i) {
  console.log('start', i);
  await callToDB(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:

function callToDB(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function startFunc (i) {
  console.log('start', i);
  await callToDB(1000);
  console.log('end', i);
}

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.