[英]Not able to understand why this code yield this output
我正在网上做一个反应课程。 在 function 链接主题之后,有一个 mcq 来预测 output。 代码是:
function job() { return new Promise(function(resolve, reject) { reject(); }); } let promise = job(); promise.then(function() { console.log('Success 1'); }).then(function() { console.log('Success 2'); }).then(function() { console.log('Success 3'); }).catch(function() { console.log('Error 1'); }).then(function() { console.log('Success 4'); });
但是为什么这段代码会产生Error 1,Success 4
为 output?
.catch
将导致将已解析的 Promise 传递到链的下一步 - 除非.catch
处理程序本身抛出。 也就是说,给定任何:
.catch(someCallback)
.then(someFn);
除非someCallback
抛出错误(这将导致被拒绝的 Promise,这可以通过.catch
进一步调用),否则无论如何, someFn
将始终运行。
这是许多人选择将.catch
放在 Promise 链的最末端的原因之一——它使控制流更容易理解。
function job() {
return new Promise(function(resolve, reject) {
reject();
});
}
let promise = job();
your promise is the result of job(), if you see your promise is rejected via reject()
, it means it will go through to .catch
, and since catch also return a promise, it will go to all then
s after catch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.