本文介绍了如何在一个循环中返回许多承诺,等待所有人做其他的事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,它调用一个异步执行的方法。这个循环可以多次调用该方法。在这个循环之后,我有另一个循环,只有当所有异步的东西完成时才需要执行。所以这说明了我的想法:

  for(i = 0; i< 5; i ++){
doSomeAsyncStuff ;
}

for(i = 0; i doSomeStuffOnlyWhenTheAsyncStuffIsFinish();
}

我不太熟悉承诺,所以任何人都可以帮助我实现这是吗?



这是我的 doSomeAsyncStuff()的行为:

  doSomeAsyncStuff {
var editor = generateCKEditor();
editor.on('instanceReady',function(evt){
doSomeStuff();
//应该有我认为的promes的resolve()
})
}

也许我必须这样做:

  doSomeAsyncStuff {
var editor = generateCKEditor();
return new Promises(function(resolve,refuse){
editor.on('instanceReady',function(evt)){
doSomeStuff();
resolve(true);
})
}
}

但我不知道

解决方案

您可以使用 Promise.all ( spec ,):它接受一堆个人承诺,并给出你所提供的所有答案都被解决了,或者当任何一个被拒绝时被拒绝的一个承诺。



所以如果你使 doSomeAsyncStuff 返回承诺,然后:

  var promises = []; $ b $ (i = 0; i  promises.p USH(doSomeAsyncStuff()); 
}

Promise.all(promises)
.then(()=> {
for(i = 0; i< 5; i +){
doSomeStuffOnlyWhenTheAsyncStuffIsFinish();
}
})
.catch((e)=> {
// handle errors here
});

Axel Rauschmayer有一个关于承诺的好文章 here 。



这里有一个例子 - :

  function doSomethingAsync(value){
return新承诺((resolve)=> {
setTimeout(()=> {
console.log(解析+值);
resolve(value);
},Math.floor(Math.random ()* 1000));
});
}

function test(){
let i;
let promises = []; (i = 0; i promises.push(doSomethingAsync(i));


}

Promise.all(promises)
.then((results)=> {
console.log(All done,results);
})
.catch((e)=> {
//处理这里的错误
});
}

test();

(没有打扰 .catch 但是,如果您在现实世界中确实需要 .catch ,如前所示。)



示例输出(因为 Math.random ,首先可能有什么不同):

 
解决3
解决2
解决1
解决4
解决0
全部完成[0,1,2,3,4]

 

I have a loop which call a method that do stuff asynchornously. This loop can call the method many time. After this loop I have another loop that need to be execute only when all the asynchronous stuff is done. So this illustrate my wants :

for(i=0;i<5;i++){
    doSomeAsyncStuff();
}

for(i=0;i<5;i++){
    doSomeStuffOnlyWhenTheAsyncStuffIsFinish();
}

I'm not familiar so much with promises so could anyone help me to achieve this?

This is how my doSomeAsyncStuff() behave :

doSomeAsyncStuff{
    var editor = generateCKEditor();
    editor.on('instanceReady',function(evt){
        doSomeStuff();
        // There should be the resolve() of the promises I think.
    })
}

Maybe I have to do something like that :

doSomeAsyncStuff{
    var editor = generateCKEditor();
    return new Promises(function(resolve,refuse){
        editor.on('instanceReady',function(evt){
            doSomeStuff();
            resolve(true);
        })
    }
}

But I'm not sure of the syntax.

解决方案

You can use Promise.all (spec, MDN) for that: It accepts a bunch of individual promises and gives you back a single promise that is resolved when all of the ones you gave it are resolved, or rejected when any of them is rejected.

So if you make doSomeAsyncStuff return a promise, then:

var promises = [];

for(i=0;i<5;i+){
    promises.push(doSomeAsyncStuff());
}

Promise.all(promises)
    .then(() => {
        for(i=0;i<5;i+){
            doSomeStuffOnlyWhenTheAsyncStuffIsFinish();
        }
    })
    .catch((e) => {
        // handle errors here
    });

Axel Rauschmayer has a good article on promises here.

Here's an example - live copy on Babel's REPL:

function doSomethingAsync(value) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Resolving " + value);
      resolve(value);
    }, Math.floor(Math.random() * 1000));
  });
}

function test() {
  let i;
  let promises = [];

  for (i = 0; i < 5; ++i) {
    promises.push(doSomethingAsync(i));
  }

  Promise.all(promises)
      .then((results) => {
        console.log("All done", results);
      })
      .catch((e) => {
          // Handle errors here
      });
}

test();

(Didn't bother with .catch on that, but you do want .catch on your real-world ones, as shown earlier.)

Sample output (because of the Math.random, what finishes first may vary):

Resolving 3
Resolving 2
Resolving 1
Resolving 4
Resolving 0
All done [0,1,2,3,4]

这篇关于如何在一个循环中返回许多承诺,等待所有人做其他的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:24