我一直在阅读使用蓝鸟的承诺,并一直试图实现以下目标:
我需要运行func1和func2直到循环结束。一旦完成,我想运行func3。代码如下:
注意:所有函数都有回调函数(表明操作已成功完成)
var jsObj = ["1", "2", "3", "4", "5"]; // has 5 elements
for (var i = 0; i < jsObj.length; i++) {
var arr1 = [];
arr1 = jsObj[i];
func1(arr1).then(function(returnVal1) {
// finished func1
func2(returnVal1).then(function(returnVal2) {
// finished func2
});
});
} // end of loop
// Now, I need to run the last function once the loop is complete
var data = ["1222"];
func3(data, function() {
alert("all done");
});
func1和func2是使用promises完成的,结果在回调函数变量returnVal1和returnVal2中返回。如何将这三个链接/压缩在一起,以便在循环中依次运行,然后使用promises运行func3?
干杯。
答案 0 :(得分:2)
将数据映射到promises,然后使用promise.all:
var jsObj = ["1", "2", "3", "4", "5"]; // has 5 elements
var promises = jsObj.map(function(obj){
return func1(obj).then(function(value){
return func2(value).then(function(val){
return val;
});
});
});
Promise.all(promises).then(function(results){
alert("all done");
});
你也可以链接承诺,例如:
.then(a=>b(a)).then(b=>c)
而不是
.then(a=>b(a).then(b=>c))
答案 1 :(得分:0)
var jsObj = ["1", "2", "3", "4", "5"]; // has 5 elements
for (var i = 0; i < jsObj.length; i++) {
func1(jsObj[i]).then(function(returnVal1) {
// finished func1
func2(returnVal1).then(function(returnVal2) {
// finished func2
finalFn();
});
});
} // end of loop
// Now, I need to run the last function once the loop is complete
var count = 0;
function finalFn(){
count++;
if(count == jsObj.length){
var data = ["1222"];
func3(data, function() {
alert("all done");
});
}
}