简体   繁体   English

循环链接JavaScript许诺-蓝鸟

[英]Chaining JavaScript promises in a loop - bluebird

I have been reading up on promises using bluebird and have been trying to achieve the following: 我一直在阅读有关使用bluebird的诺言,并试图实现以下目标:

I need to run func1 and func2 till the loop is over. 我需要运行func1和func2,直到循环结束。 Once that's done, I would like to run func3. 完成后,我想运行func3。 The code is as follows: 代码如下:

Note: All the functions have a callback function (to show that the operation has completed successfully) 注意:所有函数都有一个回调函数(以表明操作已成功完成)

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 and func2 are done using promises whereby the result is returned in the callback function variables returnVal1 and returnVal2. func1和func2是使用promises完成的,从而在回调函数变量returnVal1和returnVal2中返回结果。 How can I chain/condense these three together so that one runs after the other in a loop and then runs func3 using just promises? 如何将这三个链接/压缩在一起,以便一个循环一个接一个地运行,然后仅使用promises运行func3?

Cheers. 干杯。

Map the data to promises, then use promise.all: 将数据映射到promise,然后使用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");
});

You may also chain the promises eg: 您也可以链接承诺,例如:

.then(a=>b(a)).then(b=>c)

instead of 代替

.then(a=>b(a).then(b=>c))
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");
     });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM