Wait in for loops for async function

拜拜、爱过 提交于 2019-12-13 19:09:11

问题


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);
}

回答1:


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()
  );


来源:https://stackoverflow.com/questions/54584363/wait-in-for-loops-for-async-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!