[英]Knexjs and es6 Try/Catch causing an Unhandled Promise Rejection Warning?
[英]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") })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.