javascriptnode.jsnode-request

How can I call a function only once all requests have finished?


I am currently generating a few requests using the npm package request like this:

for (var i = 0; i < array.length; i++) {

    var options = {
        url: '...',
        headers: {
            '...'
        }
    };
    function callback(error, response, body) {

    };
    request(options, callback);

}


function toBeCalledWhenAllRequestsHaveFinished() {

}

I just don't know how to call toBeCalledWhenAllRequestsHaveFinished() only once all requests have finished.

What should be done ?


Solution

  • I would highly recommend using node-fetch package.

    Reference to the original poster


    Install node-fetch using npm install node-fetch --save.

    Make a promise-returning fetch that resolves to JSON

    const fetch = require('node-fetch');
    function fetchJSON(url) {
        // Add options
        var options = {
            headers: {
                '...'
            }
        };
        return fetch(url, options).then(response => response.json());
    }
    

    Build an array of promises from an array of URLs

    let urls = [url1, url2, url3, url4];
    let promises = urls.map(url => fetchJSON(url));
    

    Call toBeCalledWhenAllRequestsHaveFinished() when all promises are resolved.

    Promise.all(promises).then(responses => toBeCalledWhenAllRequestsHaveFinished(responses));