简体   繁体   中英

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.
2) The next for loop iteration only executed after the promise resolve, with a 1 second delay.

I am doing this way but console.log prints nothing. 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. You need to chain API calls so they are run after another:

    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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM