等待循环执行异步功能

时间:2019-02-08 00:18:26

标签: javascript asynchronous async-await wait

我需要同步运行startFunc函数,并在for循环中“等待”完成任务,然后再次运行它。我不能在startFunc()中使用await。 我需要类似C#中的.wait()之类的东西 我除了结果: 开始1 结束1 开始2 结束2等...

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 个答案:

答案 0 :(得分:2)

您还需要将for循环放入async函数中,以便可以await每次调用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);
  }
})();
另一种方法是连续链接.then
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));
}

或者您可以使用.reduce并持续传递最后一个Promise作为累加器,而不是分配给外部变量:

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