DEV Community

Discussion on: 9 Promising Promise Tips

Collapse
 
nimatrazmjo profile image
Nimatullah Razmjo • Edited

Hi Kushan,

Thanks for explaining the promise in a very good way especially Promise constructor.

I have a question.

In promise all. I have five promise which runs concurrently. If promise one resolve and promise two got a problem will go directly to catch part of Promise.all. does it rollback the promise one changes or not.

I am a bit confused.

Or let's say. In Promise.all, if an error occurs to single promise. does it rollback all other promises changes?

Thanks in advance.

Collapse
 
kepta profile image
Kushan Joshi • Edited

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).