Promises.all的快速​​失败行为

时间:2019-02-23 14:19:07

标签: javascript ecmascript-6 promise es6-promise

我试图了解Promises.all的快速​​失败行为。 考虑以下示例;

let p1 = new Promise(function(resolve, reject) {
    setTimeout(
        function(){
            console.log("p1");
            resolve('p1');
        }, 500);
});

let p2 = new Promise(function(resolve, reject) {
    setTimeout(
        function(){
            console.log("p2");
            resolve('p2');
        }, 1000);    
});

let p3 = new Promise(function(resolve, reject) {
    setTimeout(
        function(){
            console.log("p3");
            resolve('p3');
        }, 1200);
});

let p4 = new Promise(function(resolve, reject) {
    setTimeout(
        function(){
            console.log("p4");
            reject('p4');
        }, 600);
});

let p5 = new Promise(function(resolve, reject) {
    setTimeout(
        function(){
            console.log("p5");
            resolve('p5');
        }, 800);
});

let promise = Promise.all([p1, p2, p3, p4, p5]);

promise

.then(function(data) {
    data.forEach(function(data) {
        cconsole.log(data);
    });
})

.catch(function(error) {
    console.error('error is', error);
});

运行上面的示例会记录 p1,p2,p3,p4,p5 然后登录 “错误是p4”

现在,我读到的有关Promise的东西都是这样;

  

Promise.all具有快速失败的行为。如果给定的承诺被拒绝,   由此产生的Promise.all承诺将被拒绝   时刻。它不会等待其他承诺完成

所以我的问题是为什么/如何记录p1,p2,p3,p4,p5

我当时以为它应该已经记录了p1(因为它小于600毫秒才被拒绝),然后只需记录“错误是p4”

我的理解哪里有错?

1 个答案:

答案 0 :(得分:4)

我认为通过以下方式可以更好地说明快速失败的行为

function logFulfilled(val) {
   console.log(val + " fulfilled");
   return val;
}
function timeout(callback, delay, val) {
    console.log(val + " created");
    setTimeout(callback, delay, val);
}
let p1 = new Promise(function(resolve, reject) {
    timeout(resolve, 500, 'p1');
}).then(logFulfilled);

let p2 = new Promise(function(resolve, reject) {
    timeout(resolve, 1000, 'p2');
}).then(logFulfilled);

let p3 = new Promise(function(resolve, reject) {
    timeout(resolve, 1200, 'p3');
}).then(logFulfilled);

let p4 = new Promise(function(resolve, reject) {
    timeout(reject, 600, 'p4');
}).catch(err => {
   console.log(err + " rejected");
   throw err;
});

let p5 = new Promise(function(resolve, reject) {
    timeout(resolve, 800, 'p5');
}).then(logFulfilled);

let promise = Promise.all([p1, p2, p3, p4, p5]);
promise.then(console.log, console.error);

请注意,在p4被拒绝之后,p5,p2和p3完成之前,您会收到Error日志。