使用一些简单的规则非常简单:
- 每当您在中创建承诺时
then
,都将其返回 -您不返回的任何承诺都不会在外面等待。 - 每当您创建多个promise时,
.all
它们就会以这种方式等待所有promise,并且其中任何一个的错误都不会消失。 - 每当您嵌套
then
s时,通常都可以在中间返回 -then
链通常最多为1层深。 - 每当执行IO时,它都应该带有承诺 -应该在承诺中,或者应该使用承诺来表明其完成。
还有一些提示:
- 映射
.map
比使用for/push
- 更好地完成 -如果您要通过函数映射值,则map
可以简洁地表达一个动作一一应用并汇总结果的概念。 - 如果是免费的,并发比顺序执行要好 -并发执行并等待它们
Promise.all
比一个接一个地执行要好-每个等待都在下一个执行之前要好。
好的,让我们开始吧:
var items = [1, 2, 3, 4, 5];var fn = function asyncMultiplyBy2(v){ // sample async action return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));};// map over forEach since it returnsvar actions = items.map(fn); // run the function over all items// we now have a promises array and we want to wait for itvar results = Promise.all(actions); // pass array of promisesresults.then(data => // or just .then(console.log) console.log(data) // [2, 4, 6, 8, 10]);// we can nest this of course, as I said, `then` chains:var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then( data => Promise.all(data.map(fn))).then(function(data){ // the next `then` is executed after the promise has returned from the previous // `then` fulfilled, in this case it's an aggregate promise because of // the `.all` return Promise.all(data.map(fn));}).then(function(data){ // just for good measure return Promise.all(data.map(fn));});// now to get the results:res2.then(function(data){ console.log(data); // [16, 32, 48, 64, 80]});


