JavaScript Promise – Definition, Meaning, & Examples
A JavaScript promise refers to the object you create from JavaScript’s built-in Promise
constructor function.
How to Create a New Promise in JavaScript
You can create a new JavaScript promise by passing a callback function into JavaScript’s built-in Promise
constructor function.
Here’s an example:
What Happens If You Invoke a Promise without Providing a Callback?
A callback function is a required argument of the Promise
constructor function. If omitted, JavaScript will throw an Uncaught TypeError
.
Here’s an example:
The snippet above throws an Uncaught TypeError
because the Promise
constructor function requires a callback function.
Promise’s State
A promise is always in one of three states:
pending
fulfilled
rejected
What is a pending promise state in JavaScript?
A pending promise means you have an unfulfilled or unrejected promise. In other words, a pending promise means you still waiting for a response concerning a specific promise.
Here’s an example:
What is a fulfilled promise state in JavaScript?
A fulfilled promise means the Promise
constructor function returned a valid value. In such a case, the promise’s state will switch from pending
to fulfilled
.
Here’s an example:
What is a rejected promise state in JavaScript?
A rejected promise means the Promise
constructor function returned an invalid value. In such a case, the promise’s state will change from pending
to rejected
.
Here’s an example:
Important Stuff to Know about JavaScript Promises
Here are three essential facts to remember while using promises in JavaScript.
- A promise is settled if it is
fulfilled
orrejected
. - A settled promise is sometimes called a resolved (or locked-in) promise.
resolve
—notfulfill
—is the recommended name for the first parameter of aPromise
constructor’s callback argument. Developers recommend “resolve” because the first parameter does not always set a value to a fulfilled promise. In other words, the first parameter can resolve a promise object to a rejected state. For instance, consider the following snippet:
In the example above, the callback’s first parameter resolved to a rejected state rather than a fulfilled one. Therefore, naming the first parameter “fulfill” would be counterintuitive.