文章出處

  如何通過使用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!

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()