Promise.prototype.then() : JavaScript then() method and how to use it

September 25, 2019

Q:  How to use then() and how to return a promise from a function and use then() ?

 

A: then() is a method in the Promise prototype that returns a promise and accepts two callback functions. One function is for the success and the other is for the failure case of the promise. If both arguments are not given or are not callback functions, still then the method would not generate any errors.

For example, here we create a new promise.

promise .then() exists hence it is a promise. .then() allows method chaining.

 

Now we will see how to use then to return a promise

It is incorrect to use then() this way as it should return inside the then also. Otherwise resolving the promise returned by then will give undefined.

 

 

It is incorrect to use the function without returning the promise returned  by then()

 

 

Returning the promise returned by then is the correct way of returning a promise from a function

 

 

If there is some kind of logic to be applied, this is the correct way of using then()

 

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *