Promise 执行顺序问题。

我参考这个地址写了一些Promise的demo,

https://developers.google.com...

当我学到到这个例子时,

https://img2.mukewang.com/5c3b2ecf00015f6a07810616.jpg

我写了一个类似的demo:

https://jsfiddle.net/weisiwu/...

不过结果的执行顺序和给出的例子不一样,请问如何修改代码才能达到同时发起多个请求,但是返回的结果仍然按顺返

回(不是Promise.all那种全部完成后才返回的,而是有完成的且该完成项前面的也都完成了就返回该项这种)?


慕桂英546537
浏览 628回答 1
1回答

猛跑小猪

改成这样就行了var timeline = [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Promise(function(resolve, reject) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve('task5<br>');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 1000);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Promise(function(resolve, reject) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve('task6<br>');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 1500);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Promise(function(resolve, reject) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve('task7<br>');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 2000);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Promise(function(resolve, reject) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve('task8<br>');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 800);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 完成后立刻输出结果,但是按照顺序输出&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeline.map(function(val) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).reduce(function(init, req) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return init.then(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return req;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).then(function(result){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.writeln(result)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, Promise.resolve());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript