使用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!

 

posted @ 2017-11-10 20:38  Jaxu  阅读(498)  评论(0编辑  收藏  举报