【问题标题】:How to write an Asynchronous Loop using Promises?如何使用 Promises 编写异步循环?
【发布时间】:2026-02-17 14:45:01
【问题描述】:

如何使用 Promises 编写同步循环?下面的两个函数都没有等待前一个循环完成后再开始......

(async ()=> {
    let arr = [3,1,2,1,2];

    const waitFor = ms => new Promise(r => setTimeout(r, ms));

    // Using Promise.all
    const firstFn = async () => { // doens't work
        return Promise.all(arr.map(async (sec) => {
            await waitFor(sec*1000);
            console.log(`waited for ${sec} seconds`);
        }));
    }
    await firstFn();

    // Using new Promise
    const secondFn = async () => {
        arr.map(sec => {
            new Promise(async (res, rej) => {
                await waitFor(sec*1000);
                console.log(`waited for ${sec} seconds`);
                res();
            });
        });
    }
    await Promise.all(secondFn());

})();

【问题讨论】:

  • secondFn () 中没有 returnmap() 中的任何一个都没有 return
  • 看到你在使用async / await 使用for (let sec of arr) {。数组函数不支持异步..
  • 您不能编写基于 Promise 的同步循环。不过,您可以编写一个异步的顺序循环。

标签: javascript asynchronous promise async-await


【解决方案1】:

map 在并行执行中处理 Promise。如果您想按顺序使用for... of,或for 的简单形式。示例:

async function something () {
  const arr = [3,1,2,1,2];
  for (let x = 0; x < arr.length; x++) {
    const sec = arr[x];
    await waitFor(sec*1000);
    console.log(`waited for ${sec} seconds`);
  }
}

【讨论】:

    【解决方案2】:

    这是一个异步函数的示例,它采用一系列异步函数并按顺序执行它们。等待一个完成,然后再移动到另一个。

    const wait =
      ms =>
        new Promise
          ( resolve =>
              setTimeout
                ( () => (console.log(`wait ${ms}`), resolve())
                , ms
                )
          );
    
    const async_chain =
      async ([fn, ...fns]) =>
        typeof fn === 'function'
          ? (await fn(), await async_chain(fns))
          : undefined;
    
    (async function main() {
    
      await async_chain
        ( [ async () => wait(1000)
          , async () => wait(2000)
          , async () => wait(3000)
          ]
        )
    
    })();

    【讨论】:

      【解决方案3】:

      您不必为此使用承诺。您可以为此使用for..of 循环:

      for await (const sec of arr){
        await waitFor(sec*1000);
        console.log(`waited for ${sec} seconds`);
      }
      

      您可以在此处了解有关 async for of 循环的更多信息。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

      【讨论】:

      • 谢谢。我能够使用 for 循环编写它并且它可以工作,但想知道是否也可以使用 Promises 来实现它?
      • 请使用for … of 循环,而不是for await … of 循环!
      • @wongz 代码使用了 Promise,waitFor 确实返回了一个