使用Q进行同步的Promises操作
如何通過使用Q來并發(fā)執(zhí)行多個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上面的代碼輸出結(jié)果為1。很顯然,你不能簡單地將各個promises都放到一個Q()函數(shù)里來執(zhí)行,這樣只有第一個promise會被正確地執(zhí)行,剩余的都會被忽略掉。
你可以使用Q.all來代替上面的方法,它們之間的主要區(qū)別是前者將每個promise單獨作為參數(shù)進(jìn)行傳遞,而Q.all則接收一個數(shù)組,所有要并行處理的promise都放到數(shù)組中,而數(shù)組被作為一個獨立的參數(shù)傳入。
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]上面的代碼輸出結(jié)果為[1, 2, 3]。所有的promises都被正確執(zhí)行,但是你發(fā)現(xiàn)Q.all返回的結(jié)果依然是一個數(shù)組。我們也可以通過下面這種方式來獲取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返回一個個獨立的值而非數(shù)組。和返回數(shù)組結(jié)果的方式相同,這種方式返回結(jié)果的順序和傳入的數(shù)組中的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執(zhí)行失敗,被rejected或者throw error,我們?nèi)绾翁幚礤e誤呢?
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不會再繼續(xù)執(zhí)行。如果你想等待所有的promises都執(zhí)行完后再確定返回結(jié)果,你應(yīng)當(dāng)使用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!?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的使用Q进行同步的Promises操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理解工作流系统参考模型
- 下一篇: MySQL 4到5的快速升级