0

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 ?

TheProgrammer
  • 1,409
  • 4
  • 24
  • 53

1 Answers1

1

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));
Alex
  • 2,164
  • 1
  • 9
  • 27