Promise object (JavaScript)

From Wiki @ Karl Jones dot com
Revision as of 09:12, 25 September 2016 by Karl Jones (Talk | contribs)

Jump to: navigation, search

In JavaScript, the promise object is used for asynchronous computations.

A Promise represents a value which may be available now, or in the future, or never.

A promise is composable, making it more complex than a callback function.

Description

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise for the value at some point in the future.

A Promise is in one of these states:

  • pending: initial state, not fulfilled or 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 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.

Diagram

The diagram below illustrates the Promise object and related entities:

left|600px|thumb|Diagram illustrating the Promise object and related entities.

See also

External links


YouTube videos