[英]In Promise of es6, '.catch(rejection)' is equal to '.then(null,rejection)'?
Firstly,please look at this demo. 首先,请看这个演示。
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="">
In this demo, I think that "error" can't be printed. 在这个演示中,我认为无法打印“错误”。 The fact hurts me.
事实伤害了我。
Recently,I'm studying Promise by url . 最近,我正在通过网址学习Promise。
But this demo seems conflictive to that. 但这个演示似乎与此相矛盾。
I'm confused. 我糊涂了。
If you use catch
: 如果你使用
catch
:
.catch(function() {
console.log("error")
throw new Error('couldnt load image' + url);
})
both an error occurring during image load and inside success
callback: 在图像加载和内部
success
回调期间发生的错误:
someImgEle.src = url;
someImg.style.display = "block";
someImg.accessUndefinedProperty.oneLevelMore; // TypeError: Cannot read property 'oneLevelMore' of undefined
will be catched. 将被抓住。
If you use error callback
instead of a catch
clause, only error during image load will be catched. 如果使用
error callback
而不是catch
子句,则只会catch
图像加载期间的错误。 The general recomendation is to use catch
instead of error callbacks. 一般推荐是使用
catch
而不是错误回调。
Update: 更新:
In your particular case, you have an error here: 在您的特定情况下,您在此处有错误:
someImg.style.display = "block";
since someImg
is not defined, the catch
block is executed. 由于
someImg
,因此执行catch
块。 You can inspect an error by simply passing error
object in catch
block: 您只需在
catch
块中传递error
对象即可检查错误:
.catch(function(error) {
^^^^^
This particular case demonstrates why catch
is preferred to error callback
. 这个特例说明了为什么
catch
优先于error callback
。
Is
.catch(rejection)
equal to.then(null,rejection)
?.catch(rejection)
等于.catch(rejection)
.then(null,rejection)
?
Yes. 是。 And not only equal to, it's even implemented in terms of
then
. 而且不只是等于,它甚至在以下方面实现
then
。
However: 然而:
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") })
That's accurate. 那很准确。
.then(…).catch(…)
and .then(…, …)
are not equal . .then(…).catch(…)
和.then(…).catch(…)
.then(…, …)
不相等 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.