may
may

Reputation: 33

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.

But this demo seems conflictive to that.

I'm confused.

Upvotes: 3

Views: 100

Answers (2)

Bergi
Bergi

Reputation: 664307

Is .catch(rejection) equal to .then(null,rejection)?

Yes. And not only equal to, it's even implemented in terms of 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.

Upvotes: 1

Max Koretskyi
Max Koretskyi

Reputation: 105449

If you use catch:

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

both an error occurring during image load and inside success callback:

  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. The general recomendation is to use catch instead of error callbacks.

Update:

In your particular case, you have an error here:

someImg.style.display = "block";

since someImg is not defined, the catch block is executed. You can inspect an error by simply passing error object in catch block:

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

This particular case demonstrates why catch is preferred to error callback.

Upvotes: 2

Related Questions