How to .catch a Promise.reject

吃可爱长大的小学妹 提交于 2019-12-01 14:58:54

    function test() {
        return new Promise((resolve, reject) => {
        return reject('rejected')
      })
    }

    test().then(function() {
      //here when you resolve
    })
    .catch(function(rej) {
      //here when you reject the promise
      console.log(rej);
    });

Make sure every call to a then() returns a value.

For e.g.

var url = 'https://www.google.co.in';
var options = {};
var resolves = Promise.resolve();

resolves.then(() => {
  console.log('Resolved first promise');
  var fetchPromise = fetch(url, options);
  fetchPromise.then(() => {
    console.log('Completed fetch');
  });
})
.catch(error => {
  console.log('Error', error);
});

Notice the console shows an uncaught exception. However, if you returned the inner promise (or any other value, which ends up turning into a promise via resolve), you end up flattening the promise so exception bubble up.

var url = 'https://www.google.co.in';
var options = {};
var resolves = Promise.resolve();

resolves.then(() => {
  console.log('Resolved first promise');
  var fetchPromise = fetch(url, options);
  return fetchPromise.then(() => {
    console.log('Completed fetch');
  });
})
.catch(error => {
  console.log('Error', error);
});

Notice the exception bubbles up to the outer promise. Hope this clears up things a little bit.

Promise rejections fall to the second param of the then function.

function test() {
    return new Promise((resolve, reject) => {
    return reject('rejected')
  })
}

test().then(function() {
  //here when you resolve
}, function(rej) {
  //here when you reject the promise
    console.log(rej)
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!