[英]Promises and arrays in Node.js
I am using Bluebird and request npm packages: 我正在使用Bluebird并请求npm软件包:
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
Promise.promisifyAll(request);
I have a function that goes out to a REST endpoint and returns some data: 我有一个功能,可以转到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
is an array that gets returned by the REST endpoint. response
是一个由REST端点返回的数组。 The problem is that now I'd like to make a second request for each item in my array, so something like: 问题是,现在我想对数组中的每个项目再次发出请求,如下所示:
var getIndividualData = function(data) {
data.forEach(function(d) {
options.url = 'http://my/endpoint/d'; //make individual requests for each item
return request(options);
});
};
The above of course does not work and I understand why. 以上当然是行不通的,我知道为什么。 However, what I don't understand is how can I make this work.
但是,我不了解的是如何进行这项工作。 Ideally what I'd like to have is a chain such as:
理想情况下,我想要的是一条链,例如:
getData().then(function(response) {
return getIndividualData(response);
}).then(function(moreResponse) {
console.log(moreResponse); // the result of the individual calls produced by getIndividualData();
});
You can use Promise.all to wait for an array of promises to complete. 您可以使用Promise.all等待一系列的诺言完成。
getData()
.then(getIndividualData)
.then(function(moreResponse) {
// the result of the individual calls produced by getIndividualData();
console.log(moreResponse);
});
function getIndividualData(list) {
var tasks = list.map(function(item) {
options.url = // etc.
return request(options);
});
return Promise.all(tasks);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.