简体   繁体   English

Promise 在带有 setTimeout 的 for 循环内

[英]Promise inside for loop with setTimeout

I have code like follow.我有如下代码。 What i intend to do is:我打算做的是:
1) For loop and call api with sequence. 1)for循环并按顺序调用api。
2) The next for loop iteration only executed after the promise resolve, with a 1 second delay. 2) 下一个 for 循环迭代仅在 promise 解析后执行,延迟 1 秒。

I am doing this way but console.log prints nothing.我正在这样做,但 console.log 什么也没打印。 What is the correct way to approach it?处理它的正确方法是什么?

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

Your code basically runs 10000000 api requests simultaneously after 1 second delay.您的代码在 1 秒延迟后基本上同时运行 10000000 个 api 请求。 You need to chain API calls so they are run after another:您需要链接 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();

I suggest to try using async/await if possible in your situation, it greatly simplifies things.如果可能的话,我建议在您的情况下尝试使用 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