Search code examples
node.jsjsonnode-fetch

Looping through a fetch operation in Node JS


I'm trying to write a collection of Json objects into an array whilst looping through a fetch operation in Node JS. I'm sure the issue is something to do with it being an Async operation, but can't figure out how to get round it.

This is my code:

    for (const car of carFilter) {
        const carJson = fetch(modelUrl + car, settings)
            .then(res => res.json())
            .then((json.data.trim));
        carData.push(carJson);
    }
    console.log(carData);

All I'm getting from the console.log is:

 Promise { <pending> },
 Promise { <pending> },... etc

Which I presume means I'm trying to do the console.log before the data has been push into the array. I may be wrong.

Thanks in advance.


Solution

  • You can do something like this:

        const promises = [];
        for (const car of carFilter) {
            const carJson = fetch(modelUrl + car, settings)
            promises.push(carJson);
        }
    
        Promise.all(promises)
        .then((values) => {
    
        console.log(values); // will be in same order they are called 
        console.log(values[0]); // will be an Array
    
        })
        .catch( e => console.log(e));
    
    

    So, When we call out an async operation, it returns a Promise(in this case). We are pushing all the promises in an array and can use "Promises.all" that can help to wait for all of them to resolve and gives results.

    Note: if any of your promise will be rejected, you won't be able to get the subsequent promises resolved or rejected.

    Sample one is here:

     const promises = [];
        for (let i = 0; i < 10; i++) {
            const carJson = promiseCall(); //any promise call
            promises.push(carJson);
        }
    
        Promise.all(promises)
        .then((values) => {
        console.log(values); // will be in same order they are called 
    
        })
        .catch( e => console.log(e));
    
        function promiseCall () {
    
        return new Promise((res, rej) => {
                            setTimeout(()=> {
                                    res(true);
                            } ,1000);
                })
    }