我有用nodejs编写的代码让我感到困惑 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();
});
我希望循环内的第二个函数中的数据可以推入结果
所以我以前的数据是这样的
[
{
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个数据的语句有什么解决方案?
而不是deferred.resolve()
在将立即解决的数组上使用Q.all
,而是使用等待一个promise数组:
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;
});
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句