DEV Community

Michael Butak
Michael Butak

Posted on

Promises in JavaScript

What is a Promise?

A promise in JavaScript is a mechanism for handling asynchronous code (like a disk read or a network request). What does that mean? A synchronous method returns its resultant value immediately (immediately meaning as soon as it’s done evaluating the expressions it contains). An asynchronous method doesn’t return its value immediately. It has to wait for something else to complete (https request, etc.) before it has an “answer”. Because JavaScript is single-threaded, and it can only process instructions in a single sequence, one-command-at-a-time, this presents a problem when one of those commands is asynchronous. Any tasks subsequent to it requiring as an input the result of our asynchronous operation are liable to evaluate their expressions before that value is available and our code will fail.

Promises present a solution to this problem. They make asynchronous code behave more like synchronous code. The way they do this is to give the asynchronous code something else to immediately return as soon as it is evaluated while waiting for the resultant value. What is this something else it returns instead? A promise. The promise stands as a proxy to the final value until the final value becomes available. And to this promise object we may attach callback functions which do not get invoked before the completion of the current run of the event loop. This means, the final value will be available at the time when those callbacks are invoked. (This is critical for understanding promises.)

A promise contains state that is not accessible to any function but the async operation that created it. The state is either pending, fulfilled, or rejected. Pending is the initial state of the promise. It has neither been fulfilled nor rejected. Fulfilled means the asynchronous operation has completed successfully. Rejected means the operation failed. We can instruct the promise to call different callbacks based on whether the promise settles in a fulfilled or rejected state.

These callbacks are added to the runtime message queue by the promises’ .then and .catch methods. (See diagram here) I have found this understanding helpful in the practical implementation of promises.

A site for practical examples of how to use promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

A site with a fascinating introduction to combining promises with event emitters: https://www.jpwilliams.dev/using-eventemitters-to-resolve-promises-from-afar-in-nodejs

Feel free to improve upon this explanation by leaving a comment.

Top comments (0)