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

Get data from API and continue when done

我在对 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); // []

谢谢!

使用 promisesObject.values

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

另一个假设是在您的原始代码中 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);
});

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

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