Yiz*_*zhe 4 javascript promise
我一直很好奇,如果承诺在任何位置遭到拒绝,以下是否then()还会被执行?以下面的代码为例:
Promise.reject('reJECTed')
.then(() => {
console.log('before resolve()');
return Promise.resolve('reSOLVed');
})
.then((msg) => {
console.log('reSOLVed inside 1st then()');
console.log(msg);
}, (msg) => {
console.log('reJECTed inside 1st then()');
console.log(msg);
})
.then((msg) => {
console.log('reSOLVing inside 2nd then()');
console.log(msg);
}, (msg) => {
console.log('reJECTing inside 2nd then()');
console.log(msg);
})
.catch((msg) => {
console.log('reJECTed in catch()');
console.log(msg);
});
Run Code Online (Sandbox Code Playgroud)
它会打印出来
reJECTed inside 1st then()
reJECTed
reSOLVing inside 2nd then()
undefined
Run Code Online (Sandbox Code Playgroud)
在控制台上,这意味着resolve()第二个then()和最后一个catch()没有被执行.是否遇到了当的意思是reject(),任何下列resolve()内A S then()完全跳过,直至拒绝被抓?
谢谢你的解释!
这是否意味着当遇到reject()时,then()中的任何后续resolve()被完全跳过,直到捕获被拒绝?
是.当promise拒绝时,链中的所有解析处理程序都会被跳过,直到某个拒绝处理程序处理拒绝并将promise链更改回来实现.
而且,如果您没有意识到,.then()处理程序的第二个参数是拒绝处理程序(与处理程序几乎相同.catch()).
但是,请记住,如果您有拒绝处理程序而它没有throw或返回被拒绝的承诺,那么由于您已"处理"拒绝,链将再次履行.它与...完全一样try/catch.如果您catch不重新抛出,则处理异常并在此之后继续正常执行.
因此,在您输出的拒绝处理程序中reJECTed inside 1st then(),您不会返回任何内容,因此在此时,承诺链将得到满足.此时拒绝已被"处理",承诺链现在切换到履行状态.
这是你的代码的一些注释:
Promise.reject('reJECTed')
.then(() => {
// this fulfilled handler is skipped because the promise chain is rejected here
console.log('before resolve()');
return Promise.resolve('reSOLVed');
})
.then((msg) => {
// this fulfilled handler is skipped because the promise chain is rejected here
console.log('reSOLVed inside 1st then()');
console.log(msg);
}, (msg) => {
// this reject handler is called because the promise chain is rejected here
console.log('reJECTed inside 1st then()');
console.log(msg);
// because this does not rethrow or return a rejected promise
// the promise chain switches to fulfilled
})
.then((msg) => {
// this fulfilled handler is called because the promise chain is fulfilled now
console.log('reSOLVing inside 2nd then()');
console.log(msg);
}, (msg) => {
// this reject handler is not called because the promise chain is fulfilled now
console.log('reJECTing inside 2nd then()');
console.log(msg);
})
.catch((msg) => {
// this reject handler is not called because the promise chain is fulfilled now
console.log('reJECTed in catch()');
console.log(msg);
});
Run Code Online (Sandbox Code Playgroud)
让我举一个例子来说明一个promise链如何切换状态:
Promise.reject("Hello").then(val => {
console.log("1: I am not called");
}).catch(err => {
console.log("2: I am rejected");
// rethrow to keep promise chain rejected
throw err;
}).catch(err => {
console.log("3: I am still rejected");
// return normal value, promise chain switches to fulfilled
return "GoodBye";
}).then(val => {
console.log("4: Now back to fulfilled state");
}).catch(err => {
console.log("5: Not called");
});Run Code Online (Sandbox Code Playgroud)