简体   繁体   中英

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 ?

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

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