簡體   English   中英

如何使用 Promises 編寫異步循環?

[英]How to write an Asynchronous Loop using Promises?

如何使用 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());

})();

map 在並行執行中處理承諾。 如果您想按順序使用for... offor的簡單形式。 例子:

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

這是一個異步 function 的示例,它采用異步函數列表並按順序執行它們。 等待一個完成,然后再移動到另一個。

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

您不必為此使用 promise。 您可以為此使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM