有 3 个功能,第一个是我的 promise 。
fnGetIps : function () {
return new Promise(function(resolve, reject) {
var err = [], path = getBaseUrl();
restGet(path + NAMES, function (res, edges) {
if (res === undefined) {
reject("Unable to get data");
} else {
resolve(edges);
}
});
});
},
第二个是我兑现 promise 的地方。
fnGetData: function(obj){
var promise_holder;
for (property in obj) {
if (obj.hasOwnProperty(property)) {
if(condition){
promise_holder = fngetip();
}
if(condition2){
//some other code
}
}
}
promise_holder.then(function (ifChildren) {
obj.children = ifChildren;
}, function (err) {
console.error(err);
});
}
最后是我调用 fnGetData 的函数
TopoTree : function(children) {
var treeArray;
for (i = 0; i < children[i]; i++) {
fnGetData(children[i]);
}
treeArray.push(treeData);
return treeArray;
},
在 fnGetData
的所有 promise 都得到解决之前,我不想返回 TreeArray
。
如何等待所有promise先解决然后返回数据?
我无法使用promise.All
,因为我在topotree
范围内没有promise_holder
,或者我的思考方向错误?
最佳答案
你想要Promise.all()
.
让 fnGetData
返回 promise_holder
并让 TopoTree
将它们收集到数组中,并将完成逻辑放入Promise.all()
fnGetData: function(obj){
var promise_holder;
for (property in obj) {
if (obj.hasOwnProperty(property)) {
if(condition){
promise_holder = fngetip();
}
if(condition2){
//some other code
}
}
}
// RETURN THE PROMISE HERE!
return promise_holder.then(function (ifChildren) {
obj.children = ifChildren;
// Return a value for use later:
return ifChildren;
});
}
TopoTree : function(children) {
var promises = [];
for (i = 0; i < children.length; i++) {
promises.push(fnGetData(children[i]));
}
// We are handling the result / rejections here so no need to return the
// promise.
Promise.all(promises)
.then(function(treeArray) {
// Do something with treeArray
})
.catch(function(error) {
console.log(error);
});
},
关于javascript - 如何等待所有promise都解决后再返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30241881/