1.

What is the output of the below code and why?

Answer»

Nested promises are set of promises in which , the result of one promise we call another in the .then statement. It is very USEFUL in practical applications, where the result of fetch from an API endpoint will result in sending the data to another endpoint. Nested promises can also be done with callback functions, but the code get complicated soon.

Let’s look at an example of nested promises. Here we have THREE functions which return promises- movieTicketQueue, buyPopcorn and happyPartner. Now only the movieTicketQueue is returning resolve() or reject() depending on random NUMBER. The other two functions are returning only resolve() for simplicity sake.

Now, when the movieTicketQueue function is run and return a resolve(), then the IMMEDIATE .then block will be run or else we will go to the .catch block. In the .then we are returning the next buyPopcorn and in its .then we are returning the happyPartner. We are passing the message from one function to other, so it will be appended.

On running the code and getting a resolve, because we random number greater than 0.5, we get below output. 

On running the code and getting a reject, because we random number less than 0.5, we get below output.



Discussion

No Comment Found