Q Promise Node.js如何循环解析 [英] Q Promise Nodejs how to resolve in loop
本文介绍了Q Promise Node.js如何循环解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用nodejs编写的代码让我使用Q Promises
i have code written in nodejs make me confusying using Q Promises
theFunction()
.then(function(data) {
var deferred = Q.defer()
var result = [];
for(i=0; i < data.length; i++) {
secondFunc(data.item)
.then(function(data2) {
data.more = data2.item
});
result.push(data);
}
deferred.resolve(result);
deferred.promise();
});
我希望循环内第二个函数中的数据可以推入结果
i want data in second function inside loop can push into result
所以我以前的数据是这样的
so my previous data is like this
[
{
id: 1,
item: 1,
hero: 2
},
{
id: 1,
item: 1,
hero: 2
}
]
就这样
[
{
id: 1,
item: 1,
hero: 2,
more: {
list: 1
}
},
{
id: 1,
item: 1,
hero: 2,
more: {
list: 4
}
}
]
我尝试了几种输入命令的方法 deferred.resolve();循环中的语句,仅显示1个数据 有什么解决办法吗?
I've tried several ways start by entering the command deferred.resolve (); statement in the loop and only showing 1 data have any solution ?
推荐答案
使用Q.all
而不是将立即解决的数组上的deferred.resolve()
,它会等待一个promise数组:
Instead of a deferred.resolve()
on an array which will resolve immediately, use Q.all
which waits for an array of promises:
theFunction()
.then(function(data) {
var result = [];
for(var i=0; i < data.length; i++) (function(i){
result.push(secondFunc(data[i].item)
.then(function(data2) {
data[i].more = data2.item;
return data[i];
}));
})(i); // avoid the closure loop problem
return Q.all(result)
});
甚至更好:
theFunction()
.then(function(data) {
return Q.all(data.map(function(item)
return secondFunc(item)
.then(function(data2) {
item.more = data2.item;
return item;
});
});
});
这篇关于Q Promise Node.js如何循环解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文