Promises

In this lesson, you will learn how a JavaScript promise and its states make asynchronous operations easier.

Introduced with ES6, promises are a new way of dealing with asynchronous operations in JavaScript.

Introduction

A promise is an object that might produce values in the future. Just like in real life, we don’t know if the promise will be kept, and we use the promise object as a placeholder while we wait for the outcome.

const promise = new Promise();

Having an object as a proxy for future values lets us write the code in a synchronous manner. We receive the promise object and continue executing the code. However, there is a bit more to it, as you will see.

The promise constructor takes one argument: a callback with two parameters, one for success (resolve) and one for fail (reject).

We need to either resolve a promise if it is fulfilled or reject it if it failed:

const promise = new Promise((resolve, reject) => { 

  // Do stuff

  if (/* fulfilled */) {
    resolve('It worked!');
  } else {
    reject(Error('It failed!'));
  } 
});

States

A promise in JavaScript is similar to a promise in real life. It will either be kept (fulfilled) or it won’t (rejected).

A promise can be:

  • pending – Initial state, not fulfilled or rejected yet

  • fulfilled – The operation succeeded, and resolve() was called.

  • rejected – The operation failed, and reject() was called.

  • settled – Has fulfilled or rejected

Get hands-on with 1000+ tech skills courses.