Promises in JavaScript

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 Software Engineer @Walmart and instructor @Udemy, working on Blockchain, and Kubernetes. I have completed CHFA, CKA, CKAD

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aditya Joshi

Aditya Joshi

129 Followers

I am a Software Engineer @Walmart and instructor @Udemy, working on Blockchain, and Kubernetes. I have completed CHFA, CKA, CKAD