The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Structure

Promises have the basic blueprint

new Promise( /* executor */ function(resolve, reject) { ... } );

A function that is passed with the arguments resolve and reject. The executorfunction is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise, respectively. The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else rejects it if an error occurred. If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.

Example

Promises don’t return values immediately. It waits for the success or failure and then returns accordingly. This lets asynchronous methods return values like synchronous ones. Instead of returning values right away, async methods supply a promise to return the value.

Chaining Promises

The idea of the promise chaining is that the result is passed through the chain of .then handlers.

The value is returned to the next .then handler. From the output the, you can infer that return statement is passing the value to next .then handler

Conclusion

This was just a basic gist of JavaScript promises. Promises can do a lot more if used in the right way and the right place.

Hope you enjoyed reading. Connect me on Linkedin

I am a Blockchain Engineer, having a good experience in nodejs, Android, and latest technologies. I am Certified Hyperledger Fabric Administrator (CHFA)

I am a Blockchain Engineer, having a good experience in nodejs, Android, and latest technologies. I am Certified Hyperledger Fabric Administrator (CHFA)