What is State of Promise and query in Promise.all()?

Viewed 161

In the context of this article : Graceful asynchronous programming with Promises. And in section : "Running code in response to multiple promises fulfilling".

For this particular Code snippet :

function fetchAndDecode(url, type) {
   return fetch(url).then(response => {
    if (type === 'blob') {
      return response.blob();
    } else if (type === 'text') {
      return response.text();
    }
  })
  .catch(e => {
    console.log('There has been a problem with your fetch operation: ' + e.message);
  });
}

let coffee = fetchAndDecode('coffee.jpg', 'blob');
let tea = fetchAndDecode('tea.jpg', 'blob');
let description = fetchAndDecode('description.txt', 'text');


Promise.all([coffee, tea, description]).then(values => {

});

It says in article : At the end of the block, we chain on a .catch() call, to handle any error cases that may come up with any of the promises passed in the array to .all(). If any of the promises reject, the catch block will let you know which one had a problem. The .all() block (see below) will still fulfil, but just won't display the resources that had problems. If you wanted the .all to reject, you'd have to chain the .catch() block on to the end of there instead.

Why .all() block will fulfil if any Promise gets rejected? Looking at Promise.all() refrence on MDN it says .all() block will only get fulfill when all the promises will get fulfil.

Also what will be the state of promise returned by the function, if we are unable to fetch from url and we will enter .catch block, wouldn't the state of promise will still be pending in that case ??

1 Answers

Your confusion is understandable. The piece that you are missing is that the Promise.all will always succeed, because you are adding a catch to each individual promise.

So even if one of the sub-promises fails, you'll just get undefined instead of the value, but you've already handled any rejections. Once you .catch the resulting Promise is considered resolved, not rejected. If you want it to still be rejected, you can re-throw the error after logging.

Related