使用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会被正确地执行,剩余的都会被忽略掉。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的顺序也是一致的。spa

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,咱们如何处理错误呢?code

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都执行完后再肯定返回结果,你应当使用allSettledblog

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!
相关文章
相关标签/搜索