Nodejs Synchronous For each loop

后端 未结 6 1561
刺人心
刺人心 2020-12-28 15:51

I want to do a for each loop but have it run synchronously. Each iteration of the loop will do an http.get call and that will return json for it to insert the values into a

6条回答
  •  粉色の甜心
    2020-12-28 16:31

    Just wrap the loop in an async function. This example illustrates what I mean:

    const oneSecond = async () => 
        new Promise((res, _) => setTimeout(res, 1000));
    

    This function completes after just 1 second:

    const syncFun = () => {
        for (let i = 0; i < 5; i++) {
            oneSecond().then(() => console.log(`${i}`));
        }
    }
    
    syncFun(); // Completes after 1 second ❌
    

    This one works as expected, finishing after 5 seconds:

    const asyncFun = async () => {
        for (let i = 0; i < 5; i++) {
            await oneSecond();
            console.log(`${i}`);
        }
    }
    
    asyncFun(); // Completes after 5 seconds ✅
    

提交回复
热议问题