从API获取数据并在完成后继续

时间:2017-03-02 08:11:29

标签: javascript node.js asynchronous request underscore.js

我遇到了在nodejs中循环获取api请求的问题。我想从多个端点获取数据,并在完成所有请求后继续。我试过这样的东西,但它运行异步并记录一个空数组。任何提示如何确定所有请求何时准备就绪?

var api_endpoints = { "1": "url1", "2": "url2", "3": "url3" };

var allApiSources = [];
_.each(api_endpoints, function (val, key) {
    request(val, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var data = JSON.parse(body);
            _.each(data.url, function (val, key) {
                allApiSources.push(value);
            });
        }
    });
});
console.log(allApiSources); // []

谢谢!

2 个答案:

答案 0 :(得分:2)

使用promisesObject.values

一个假设...... data.url是一个Object,而不是一个数组

另一个假设是,原始代码allApiSources.push(value);应该是allApiSources.push(val);

var api_endpoints = { "1": "url1", "2": "url2", "3": "url3" };

Promise.all(Object.values(api_endpoints).map(value => new Promise((resolve, reject) => {
    request(value, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var data = JSON.parse(body);
            // you can remove the Object.values call if data.url is an Array
            return Object.values(data.url);
        }
        reject(error || response.statusCode);
    });
})))
.then(results => [].concat(...results)) // flattens the array of arrays
.then(allApiSources => {
    console.log(allApiSources);
});

答案 1 :(得分:0)

您需要使用async npm,因为调用是异步的,您将无法打印值,async模块允许您运行多个异步调用,然后将结果映射到单个数组

http://caolan.github.io/async/

async.map(['url1','url2','url3'], request, function(err, allApiSources) {
      console.log(allApiSources); // []

    // allApiSources is now an array of responses for each request
});