簡體   English   中英

Promise 在帶有 setTimeout 的 for 循環內

[英]Promise inside for loop with setTimeout

我有如下代碼。 我打算做的是:
1)for循環並按順序調用api。
2) 下一個 for 循環迭代僅在 promise 解析后執行,延遲 1 秒。

我正在這樣做,但 console.log 什么也沒打印。 處理它的正確方法是什么?

const axios = require('axios');

function getData(i){
    return axios.get(`http://www.api.com/${i}`);
}

for (let i = 0; i < 10000000; i++) {
    setTimeout(() => {
        getData(i)
            .then((res) => {
                console.log(`successs ${i}`);
            })
            .catch((err) => {
                console.log(`fail ${i}`);
            })
    }, 1000)
}

您的代碼在 1 秒延遲后基本上同時運行 10000000 個 api 請求。 您需要鏈接 API 調用,以便它們依次運行:

    const axios = require('axios');

    function getData(i){
        return axios.get(`http://www.api.com/${i}`);
    }

    function wait(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function dataLoop() {
       const getOne = (i: number) => {
         if (i < 10000000) {
            getData(i)
                .then((res) => {
                    console.log(`successs ${i}`);
                })
                .catch((err) => {
                    console.log(`fail ${i}`);
                })
                .then(wait(1000))
                .then(() => getOne(i + 1))
         }
       }
       getOne(0);
    }
    dataLoop();

如果可能的話,我建議在您的情況下嘗試使用 async/await,它可以大大簡化事情。

for (let i = 0; i < 10000000; i++) {
    try {
        const res = await getData(i);
        console.log(`successs ${i}`);
    } catch (e) {
        console.log(`fail ${i}`);
    }
    await wait(1000);
}

暫無
暫無

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

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