Promises, Promises

Jessica Beaver
2 min readJan 5, 2021
Getty Images

What is a Promise?

In JavaScript, like in real life, a promise is a commitment to do something — the promise is either kept (resolved) or broken (rejected). Under the hood, promises are objects with functions attached to them, which allows us to replace clunky nested functions and save us from “callback hell”.

Imagine a website is loading and we need to begin some action that will take some unknown time to resolve — this is the prefect time to use a promise.The promise will not prevent the website from loading, but the action triggered will execute in the background. When the promise settles, it will either be accepted (resolved) or rejected and both situations are accounted for.

Basic Syntax

Promises are ‘wrappers’ for any asynchronous task and have two distinct phases: creation and use. To create a promise, we use the ‘new’ keyword and the Promise constructor. The constructor takes a function parameter called the executor function which executes as soon as the constructor is called. The executor generally begins an asynchronous operation and controls how the promise should be settled. The executor function itself has two parameters — referred to as the resolve() and reject() functions — these functions themselves are not defined by the programmer, but the parameters passed in are.

To then use the promise, we can use one or more of the .then() or .catch() methods.

If the condition resolves to true, we invoke resolve() with the string ‘Success!’, if it resolves to false, we invoke reject() with the string ‘Failed’.

Conclusion

Promises can save our code from callback hell and disorganization by allowing us to attach functions to the promise object rather than as arguments for other callbacks. In asynchronous operations, they allow us to account for a temporarily unknown value so that the rest of our program can continue to run while the value either resolves or is rejected, and account for the next steps in either case.

--

--