如何仅在所有请求完成后才调用一个函数?

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

我目前正在使用 npm 包 request 生成一些请求,如下所示:

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

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

    };
    request(options, callback);

}


function toBeCalledWhenAllRequestsHaveFinished() {

}

我只是不知道如何在所有请求完成后才调用 toBeCalledWhenAllRequestsHaveFinished()

应该怎么办?

我强烈推荐使用 node-fetch 包。

Reference to the original poster


使用 npm install node-fetch --save.

安装 node-fetch

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

当所有承诺都已解决时调用 toBeCalledWhenAllRequestsHaveFinished()

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