我使用http post方法从端点获取数据以填充表。我首先需要获得收件人的id,然后我需要使用这些收件人的id从另一个端点获取属于收件人的对象。
我有一个http post返回一个承诺。使用.then,我将这些id号存储在javascript数组中。然后,我需要为数组上的每个id创建一个http post,这将返回另一个承诺。不确定这是否是最好的方法:
getRecipients = httpService.doPost("/search", [], {userId:"test"});
getRecipients.then(function(recipientData){
vm.recipients = recipientData.data.recipients;
}).then(function(){
for(x in vm.recipients)
{
httpService.doPost("/searchObjects", [], vm.recipients[x].id)
.then(function(){
//store each object returned on another array here....
});
}
});
注意:doPost(端点,未使用,参数进行搜索)使用上面的方法,问题是for循环不会等待then,一旦调用doPost就会移动到下一个迭代。
我想我可以使用蓝鸟,但不确定这是否会是最好的方式去这里,如果是这样,它应该怎么做(注意,这是服务器端javascript所以要求是不可用的每说,除非我使用require.js)?
如果我没理解错的话,你是在找这样的东西:
getRecipients = httpService.doPost("/search", [], {userId:"test"});
getRecipients.then(function(recipientData){
vm.recipients = recipientData.data.recipients;
var promises = [];
for (x in vm.recipients) {
promises.push(httpService.doPost("/searchObjects", [], vm.recipients[x].id));
}
// in this case $q.all waits for all of the requests to finish
// then gives the responses
$q.all(promises).then(function(responses) {
// responses is an array of the responses
// from each request in the promise array
});
});