使用Q进行同步的Promises操作
生活随笔
收集整理的這篇文章主要介紹了
使用Q进行同步的Promises操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如何通過使用Q來并發執行多個promises呢?
Q(Q(1), Q(2), Q(3)).then(function (one, two, three) { console.log(one);console.log(two);console.log(three);}, function (ex) {console.error(ex.stack);}); // 1上面的代碼輸出結果為1。很顯然,你不能簡單地將各個promises都放到一個Q()函數里來執行,這樣只有第一個promise會被正確地執行,剩余的都會被忽略掉。
你可以使用Q.all來代替上面的方法,它們之間的主要區別是前者將每個promise單獨作為參數進行傳遞,而Q.all則接收一個數組,所有要并行處理的promise都放到數組中,而數組被作為一個獨立的參數傳入。
Q.all([Q(1), Q(2), Q(3)]).then(function (one, two, three) {console.log(one);console.log(two);console.log(three);}, function (ex) {console.error(ex.stack);}); // [1,2,3]上面的代碼輸出結果為[1, 2, 3]。所有的promises都被正確執行,但是你發現Q.all返回的結果依然是一個數組。我們也可以通過下面這種方式來獲取promises的返回值:
Q.all([Q(1), Q(2), Q(3)]).then(function (one, two, three) {console.log(one[0]);console.log(one[1]);console.log(one[2]);}, function (ex) {console.error(ex.stack);}); // 1 // 2 // 3除此之外,我們還可以將then替換成spread,讓Q返回一個個獨立的值而非數組。和返回數組結果的方式相同,這種方式返回結果的順序和傳入的數組中的promise的順序也是一致的。
Q.all([Q(1), Q(2), Q(3)]).spread(function (one, two, three) {console.log(one);console.log(two);console.log(three);}, function (ex) {console.error(ex.stack);}); // 1 // 2 // 3那如果其中的一個或多個promsie執行失敗,被rejected或者throw error,我們如何處理錯誤呢?
Q.all([Q(1), Q.reject('rejected!'), Q.reject('fail!')]).spread(function (one, two, three) {console.log(one);console.log(two);console.log(three);}, function (reason, otherReason) {console.log(reason);console.log(otherReason);}); // rejected! // undefined如果傳入的promises中有一個被rejected了,它會立即返回一個rejected,而其它未完成的promises不會再繼續執行。如果你想等待所有的promises都執行完后再確定返回結果,你應當使用allSettled:
Q.allSettled([Q(1), Q.reject('rejected!'), Q.reject('fail!')]) .then(function (results) {results.forEach(function (result) {if (result.state === "fulfilled") {console.log(result.value);} else {console.log(result.reason);}}); }); // 1 // rejected! // fail!?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的使用Q进行同步的Promises操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理解工作流系统参考模型
- 下一篇: 云软件——艺术字符设计!【推荐】