Promises in JavaScript

Aditya Joshi
Aug 15, 2019 · 2 min read

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

Aditya Joshi

Written by

I am a Blockchain Engineer, having a good experience in nodejs, Android, and latest technologies.

More From Medium

Also tagged Advanced Javascript

Also tagged JavaScript

Also tagged Promises

Also tagged Promises

How to use JavaScript Promises

Alex Ritzcovan
Feb 17 · 6 min read
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade