【发布时间】:2015-10-28 14:28:27
【问题描述】:
我正在使用 Bluebird 并请求 npm 包:
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
Promise.promisifyAll(request);
我有一个输出到 REST 端点并返回一些数据的函数:
var getData = function() {
options.url = 'http://my/endpoint';
options.method = 'GET'; //etc etc...
return request(options);
};
getData().then(function(response) {
console.log(response); //-> this returns an array
});
response 是一个由 REST 端点返回的数组。问题是现在我想对数组中的每个项目进行第二次请求,例如:
var getIndividualData = function(data) {
data.forEach(function(d) {
options.url = 'http://my/endpoint/d'; //make individual requests for each item
return request(options);
});
};
上述当然不起作用,我明白为什么。但是,我不明白如何才能使这项工作。理想情况下,我想要的是一条链,例如:
getData().then(function(response) {
return getIndividualData(response);
}).then(function(moreResponse) {
console.log(moreResponse); // the result of the individual calls produced by getIndividualData();
});
【问题讨论】:
标签: javascript arrays node.js foreach promise