Mozilla Promise definition

Docs/Web/JavaScript/Reference/Global_Objects/Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

To learn about the way promises work and how you can use them, we advise you to read Using promises first.

Description

A Promise is a proxy for a value not necessarily known when the promise is created.

It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason.

This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

A Promise is in one of these states:

  • pending : initial state, neither fulfilled nor rejected.

  • fulfilled : meaning that the operation completed successfully.

  • rejected : meaning that the operation failed.

A pending promise can either be fulfilled with a value, or rejected with a reason (error).

When either of these options happens, the associated handlers queued up by a promise’s then method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)

As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained.

Docs/Web/JavaScript/Guide/Using_promises

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

Imagine a function, createAudioFileAsync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs.

Here’s some code that uses createAudioFileAsync():

function successCallback(result) {
  console.log("Audio file ready at URL: " + result);
}

function failureCallback(error) {
  console.error("Error generating audio file: " + error);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback);

Modern functions that return a promise, you can attach your callbacks to instead:

If createAudioFileAsync() were rewritten to return a promise, using it could be as simple as this:

createAudioFileAsync(audioSettings).then(successCallback, failureCallback);

That’s shorthand for:

const promise = createAudioFileAsync(audioSettings);
promise.then(successCallback, failureCallback);

We call this an asynchronous function call.

This convention has several advantages. We will explore each one.