簡體   English   中英

在es6的承諾中,'。catch(rejection)'等於'.then(null,rejection)'?

[英]In Promise of es6, '.catch(rejection)' is equal to '.then(null,rejection)'?

首先,請看這個演示。

 function loadImageAsync(url) { return new Promise(function(resolve, reject) { var image = new Image(); image.src = url; // onload 在對象已加載時觸發image.onload = resolve; // onerror 在文檔或圖像加載過程中發生錯誤時被觸發image.onerror = reject; }) } var someImgEle = document.getElementById("imgEle"); var url = someImgEle.dataset.src loadImageAsync(url).then(function() { someImgEle.src = url; someImg.style.display = "block"; // error will be printed }).catch(function() { console.log("error") throw new Error('couldnt load image' + url); }) /* loadImageAsync(url).then(function(){ someImgEle.src = url; someImg.style.display = "block"; // error will be not printed },function () { console.log("error") throw new Error('couldnt load image' + url); }) */ 
 <img id="imgEle" src="" data-src="http://omizt4opc.bkt.clouddn.com/avatar.jpg" alt=""> 

在這個演示中,我認為無法打印“錯誤”。 事實傷害了我。

最近,我正在通過網址學習Promise。

但這個演示似乎與此相矛盾。

我糊塗了。

如果你使用catch

.catch(function() {
  console.log("error")
  throw new Error('couldnt load image' + url);
})

在圖像加載內部success回調期間發生的錯誤:

  someImgEle.src = url;
  someImg.style.display = "block";
  someImg.accessUndefinedProperty.oneLevelMore; // TypeError: Cannot read property 'oneLevelMore' of undefined

將被抓住。

如果使用error callback而不是catch子句,則只會catch圖像加載期間的錯誤。 一般推薦是使用catch而不是錯誤回調。

更新:

在您的特定情況下,您在此處有錯誤:

someImg.style.display = "block";

由於someImg ,因此執行catch塊。 您只需在catch塊中傳遞error對象即可檢查錯誤:

.catch(function(error) {
                ^^^^^

這個特例說明了為什么catch優先於error callback

.catch(rejection)等於.catch(rejection) .then(null,rejection)

是。 而且不只是等於,它甚至在以下方面實現then

然而:

 loadImageAsync(url).then(function(){ // error here will be printed }).catch(function() { console.log("error") }) loadImageAsync(url).then(function(){ // error here will be not printed }, function () { console.log("error") }) 

那很准確。 .then(…).catch(…).then(…).catch(…) .then(…, …)不相等

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM