Promise
The Promise
object is used for deferred and asynchronous computations. A Promise
represents an operation that hasn't completed yet, but is expected in the future.
Syntax
Parameters
- executor
- Function object with two arguments
resolve
andreject
. The first argument fulfills the promise, the second argument rejects it. We can call these functions once our operation is completed.
Description
A Promise
represents 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 of having a 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 become either 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
and Promise.prototype.then
methods return promises, they can be chained—an operation called composition.Promise.prototype.catch
Properties
Promise.length
- Length property whose value is 1 (number of constructor arguments).
Promise.prototype
- Represents the prototype for the
Promise
constructor.
Methods
Promise.all(iterable)
- Returns a promise that resolves when all of the promises in the iterable argument have resolved. This is useful for aggregating results of multiple promises together.
Promise.race(iterable)
- Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
Promise.reject(reason)
- Returns a
Promise
object that is rejected with the given reason.
Promise.resolve(value)
- Returns a
Promise
object that is resolved with the given value. If the value is a thenable (i.e. has athen
method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you want to know if a value is a promise or not -Promise.resolve(value)
it instead and work with the return value as a promise.