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