re: 9 Promising Promise Tips VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION

I am not clear what you mean by rolling back.

Let us look at a modified point 7's example:


const prom1 =  fetchComments().then(comments => console.log(comments));
const prom2 = fetchPosts().then(posts => console.log(posts))


Promise.all([prom1, prom2])
.then(() => {
  console.log('Hello');
})

If I understand your doubt correctly, imagine the above situation in which there are 2 promises prom1 and prom2. Now if prom2 fails because fetchPosts fails, the following things will happen:

  • console.log(comments) would be shown to users, since promises are immutable and prom1 has nothing to do with prom2 failing.
  • console.log(posts) would NOT be shown to users, since prom2 has failed.
  • console.log('Hello') would NOT be shown to users, since it is a new promise composed of prom1 & prom2, in which prom2 has failed.

To understand Promise.all correctly. You need to understand that Promise.all creates a new promise whose outcome is dependant on the promises (eg. prom1 and prom2) it was composed with.

Let us use our previous example and this time name the new promise:

const resultPromise = Promise.all([prom1, prom2]);

// This is exactly same as the previous example, just with improved readability with the help of variable naming
resultPromise.then(() => {
  console.log('Hello');
})

The outcome of resultPromise is:

  • resolved: If all of the promises resolve.
  • rejected: If one or more promises rejects. In our example prom2 rejected and hence resultPromise would also be rejected.

Now you can clearly see the dependency of all these promises and their outcome. (btw reread the point 2, I hope this comment will make it easier).

code of conduct - report abuse