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

时间:2018-06-28 13:06:58

标签: javascript node.js fetch node-fetch

我目前正在使用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()

应该怎么做?

1 个答案:

答案 0 :(得分:1)

我强烈建议使用node-fetch软件包。

Reference to the original poster


使用node-fetch安装npm install node-fetch --save

  

进行承诺返回的解析为JSON的获取

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

从一组URL构建一个诺言

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

所有诺言都解决后,致电toBeCalledWhenAllRequestsHaveFinished()

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