Javascript 在es6的承诺中,';。捕获(拒绝)和#x27;等于';。然后(空,拒绝)';?
首先,请看这个演示Javascript 在es6的承诺中,';。捕获(拒绝)和#x27;等于';。然后(空,拒绝)';?,javascript,ecmascript-6,promise,frontend,Javascript,Ecmascript 6,Promise,Frontend,首先,请看这个演示 函数loadImageAsync(url){ 返回新承诺(功能(解决、拒绝){ var image=新图像(); image.src=url; //装载在对象已加载时触发 image.onload=解析; //一个错误在文档或图像加载过程中发生错误时被触发 image.onerror=拒绝; }) } var someImgEle=document.getElementById(“imgEle”); var url=someImgEle.dataset.src loadIm
函数loadImageAsync(url){
返回新承诺(功能(解决、拒绝){
var image=新图像();
image.src=url;
//装载在对象已加载时触发
image.onload=解析;
//一个错误在文档或图像加载过程中发生错误时被触发
image.onerror=拒绝;
})
}
var someImgEle=document.getElementById(“imgEle”);
var url=someImgEle.dataset.src
loadImageAsync(url).then(函数(){
someImgEle.src=url;
someImg.style.display=“block”;
//错误将被打印出来
}).catch(函数(){
console.log(“错误”)
抛出新错误('无法加载图像'+url);
})
/*
loadImageAsync(url).then(函数(){
someImgEle.src=url;
someImg.style.display=“block”;
//错误将不会被打印
},函数(){
console.log(“错误”)
抛出新错误('无法加载图像'+url);
})
*/
如果您使用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
而不是错误回调
更新:
在您的特定情况下,此处有一个错误:
someImg.style.display = "block";
由于未定义someImg
,因此执行catch
块。只需在catch
块中传递error
对象,即可检查错误:
.catch(function(error) {
^^^^^
这个特殊的案例说明了为什么catch
比error callback
更受欢迎
.catch(拒绝)
是否等于。然后(null,拒绝)
对。而且不仅等于,它甚至是按照然后的方式实现的
然而:
那是准确的 我不明白你为什么认为这个错误不能打印出来。要回答标题中的问题(这似乎与问题正文中的文本是分开的)。。。是的,.catch(onReject)
与完全相同。then(null,onReject)
-但与不同。then(onFulfill,onReject)
-事实上,我使用的polyfill中有这段代码Promise.prototype.catch=函数(onRejected){返回这个。then(null,onRejected);}代码>仅当发生错误时,才会执行catch。我的意思是,在图像加载和内部成功回调期间没有错误。所以我不明白捕获已经被执行了。@may,啊,我现在明白了。它被触发是因为您在“someImg.style.display=“block”`-请参阅我的最新问题。还有,别忘了,如果有帮助的话,你可以投票或接受我的答案。哦,我很抱歉。我犯了一个小但大的错误。我完全理解你说的话!事实上,我知道接球比回球要好。非常感谢!
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")
})