Key Concepts

Review core concepts you need to learn to master this subject

States of a JavaScript Promise

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

A JavaScript Promise object can be in one of three states: pending, resolved, or rejected.

While the value is not yet available, the Promise stays in the pending state. Afterwards, it transitions to one of the two states: resolved or rejected.

A resolved promise stands for a successful completion. Due to errors, the promise may go in the rejected state.

In the given code block, if the Promise is on resolved state, the first parameter holding a callback function of the then() method will print the resolved value. Otherwise, an alert will be shown.

The .catch() method for handling rejection

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

The function passed as the second argument to a .then() method of a promise object is used when the promise is rejected. An alternative to this approach is to use the JavaScript .catch() method of the promise object. The information for the rejection is available to the handler supplied in the .catch() method.

JavaScript Promise.all()

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

The JavaScript Promise.all() method can be used to execute multiple promises in parallel. The function accepts an array of promises as an argument. If all of the promises in the argument are resolved, the promise returned from Promise.all() will resolve to an array containing the resolved values of all the promises in the order of the initial array. Any rejection from the list of promises will cause the greater promise to be rejected.

In the code block, 3 and 2 will be printed respectively even though promise1 will be resolved after promise2.

Executor function of JavaScript Promise object

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

A JavaScript promise’s executor function takes two functions as its arguments. The first parameter represents the function that should be called to resolve the promise and the other one is used when the promise should be rejected. A Promise object may use any one or both of them inside its executor function.

In the given example, the promise is always resolved unconditionally by the resolve function. The reject function could be used for a rejection.

.then() method of a JavaScript Promise object

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

The .then() method of a JavaScript Promise object can be used to get the eventual result (or error) of the asynchronous operation.

.then() accepts two function arguments. The first handler supplied to it will be called if the promise is resolved. The second one will be called if the promise is rejected.

setTimeout()

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

setTimeout() is an asynchronous JavaScript function that executes a code block or evaluates an expression through a callback function after a delay set in milliseconds.

Avoiding nested Promise and .then()

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

In JavaScript, when performing multiple asynchronous operations in a sequence, promises should be composed by chaining multiple .then() methods. This is better practice than nesting.

Chaining helps streamline the development process because it makes the code more readable and easier to debug.

Creating a Javascript Promise object

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

An instance of a JavaScript Promise object is created using the new keyword.

The constructor of the Promise object takes a function, known as the executor function, as the argument. This function is responsible for resolving or rejecting the promise.

JavaScript Promise Object

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

A JavaScript Promise is an object that can be used to get the outcome of an asynchronous operation when that result is not instantly available.

Since JavaScript code runs in a non-blocking manner, promises become essential when we have to wait for some asynchronous operation without holding back the execution of the rest of the code.

Chaining multiple .then() methods

const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => alert(err));

The .then() method returns a Promise, even if one or both of the handler functions are absent. Because of this, multiple .then() methods can be chained together. This is known as composition.

In the code block, a couple of .then() methods are chained together. Each method deals with the resolved value of their respective promises.

JavaScript Promises
Lesson 1 of 1
  1. 1
    In web development, asynchronous programming is notorious for being a challenging topic. An asynchronous operation is one that allows the computer to “move on” to other tasks while waiting for …
  2. 2
    Promises are objects that represent the eventual outcome of an asynchronous operation. A Promise object can be in one of three states: *Pending: The initial state— the operation has not …
  3. 3
    Let’s construct a promise! To create a new Promise object, we use the new keyword and the Promise constructor method: const executorFunction = (resolve, reject) => { }; const myFirstPromise = new P…
  4. 4
    Knowing how to construct a promise is useful, but most of the time, knowing how to consume, or use, promises will be key. Rather than constructing promises, you’ll be handling Promise objects ret…
  5. 5
    The initial state of an asynchronous promise is pending, but we have a guarantee that it will settle. How do we tell the computer what should happen then? Promise objects come with an aptly named ….
  6. 6
    To handle a “successful” promise, or a promise that resolved, we invoke .then() on the promise, passing in a success handler callback function: const prom = new Promise((resolve, reject) => { res…
  7. 7
    One way to write cleaner code is to follow a principle called separation of concerns. Separation of concerns means organizing code into distinct sections each handling a specific task. It enables…
  8. 8
    One common pattern we’ll see with asynchronous programming is multiple operations which depend on each other to execute or that must be executed in a certain order. We might make one request to a d…
  9. 9
    Promise composition allows for much more readable code than the nested callback syntax that preceded it. However, it can still be easy to make mistakes. In this exercise, we’ll go over two common m…
  10. 10
    When done correctly, promise composition is a great way to handle situations where asynchronous operations depend on each other or execution order matters. What if we’re dealing with multiple promi…
  11. 11
    Awesome job! Promises are a difficult concept even for experienced developers, so pat yourself on the back. You’ve learned a ton about asynchronous JavaScript and promises. Let’s review: + Promises…

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo