繁体   English   中英

无法理解为什么这段代码会产生这个 output

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM