A Promise in JavaScript is an object that links “Producing Code” (code that takes time, like loading data) and “consuming code” (code that wants the result once it's ready). It allows you to handle asynchronous operations, such as fetching data from a server or reading a file, in a more manageable way.

Promise Construction

let promise = new Promise(function(resolve, reject) {
  // executor (the producing code)
});

The function passed to new Promise is called the executor. When new Promise is created, the executor runs automatically. It contains the producing code which should eventually produce the result. Inside the executor.

Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only inside the executor.

When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks:

The promise object returned by the new Promise constructor has these internal properties:

Consuming Promise

Once a promise is created, you can consume it using .then() and .catch() methods.

.then()

The .then() method is used to handle both success and failure results. It takes two functions as arguments:

promise.then(
  function(result) { /* handle success */ },
  function(error) { /* handle error */ }
);

If you're only interested in handling the successful result, you can omit the second function: