You’re reading the English version of this content since no translation exists yet for this locale. Help us translate this article!
L'objecte Promise
representa l'eventual finalització (o fracàs) d'una operació asincrònica i el seu valor resultant.
Aquesta entrada és per al constructor Promise. Per obtenir informació sobre les promeses, llegeix primer Emprant promises. El constructor s'utilitza principalment per embolcallar funcions que no admeten promises.
Sintaxi
new Promise( /* executor */ function(resolve, reject) { ... } );
Paràmetres
- executor
- Una funció que es passa amb els arguments
resolve
ireject
. La funcióexecutor
s'executa immediatament mitjançant la implementació de la Promesa, passant les funcionsresolve
ireject
(l'executor es crida fins i tot abans que el constructorPromise
retorni l'objecte creat). Les funcions deresolve
ireject
, quan es criden, resolen o rebutgen la promesa, respectivament. Normalment, l'executor inicia alguns treballs asincrònics, i després, un cop finalitzi, o bé crida a la funcióresolve
per resoldre la promesa, o bé la rebutja si s'ha produït un error. - Si es produeix un error en la funció de l'executor, la promesa és rebutjada. El valor retornat de l'executor és ignorat.
Descripció
Una Promise
és un proxy
per a un valor no necessariàment conegut quan la promesa és creada. Això us permet associar gestors amb l'eventual valor exitós o la raó de fallida d'una acció asincrònica. Això permet als mètodes asincrònics retornar valors de manera semblant als mètodes sincrònics: en lloc de retornar immediatament el valor final, el mètode asincrònic retorna una promesa que proveirà el valor en algun punt en el futur.
Una Promise
pot tenir un dels següents estats:
- pending: estat inicial, ni complerta ni rebutjada.
- fulfilled: indicant que l'operació s'ha completat amb èxit.
- rejected: indicant que l'operació ha fallat.
Una promesa pendent pot serfulfilled amb un valor, o bé rejected amb un motiu (error). Quan alguna d'aquestes opcions succeeix, els gestors associats concatenats pel mètode then
de la promesa són executats. (Si la promesa ja ha sigut complerta o rebutjada quan un gestor corresponent és adjuntat, el gestor serà cridat, evitant així un estat de competició entre una operació asíncrona essent completada i llurs gestors essent adjuntats.
As the
and Promise.prototype.then()
methods return promises, they can be chained.Promise.prototype.catch()
Not to be confused with: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes which are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider the arrow function with no arguments: f = () => expression
to create the lazily-evaluated expression, and f()
to evaluate.
Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is fulfilled. States and fates contains more details about promise terminology.
Propietats
Promise.length
- Length property whose value is always 1 (number of constructor arguments).
Promise.prototype
- Represents the prototype for the
Promise
constructor.
Metodes
Promise.all(iterable)
- Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in the same order as defined in the iterable. If the returned promise rejects, it is rejected with the reason from the first promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises.
Promise.race(iterable)
- Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills 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 don't know if a value is a promise or not,Promise.resolve(value)
it instead and work with the return value as a promise.
Promise
prototype
Properties
Promise.prototype.constructor
- Returns the function that created an instance's prototype. This is the
Promise
function by default.
Methods
Promise.prototype.catch()
- Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.
Promise.prototype.then()
- Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler
onFulfilled
oronRejected
is not a function). Promise.prototype.finally()
- Appends a handler to the promise, and returns a new promise which is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.
Creating a Promise
A Promise
object is created using the new
keyword and its constructor. This constructor takes as its argument a function, called the "executor function". This function should take two functions as parameters. The first of these functions (resolve
) is called when the asynchronous task completes successfully and returns the results of the task as a value. The second (reject
) is called when the task fails, and returns the reason for failure, which is typically an error object.
const myFirstPromise = new Promise((resolve, reject) => { // do something asynchronous which eventually calls either: // // resolve(someValue); // fulfilled // or // reject("failure reason"); // rejected });
To provide a function with promise functionality, simply have it return a promise:
function myAsyncFunction(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onload = () => resolve(xhr.responseText); xhr.onerror = () => reject(xhr.statusText); xhr.send(); }); };
Examples
Basic Example
let myFirstPromise = new Promise((resolve, reject) => { // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed. // In this example, we use setTimeout(...) to simulate async code. // In reality, you will probably be using something like XHR or an HTML5 API. setTimeout(function(){ resolve("Success!"); // Yay! Everything went well! }, 250); }); myFirstPromise.then((successMessage) => { // successMessage is whatever we passed in the resolve(...) function above. // It doesn't have to be a string, but if it is only a succeed message, it probably will be. console.log("Yay! " + successMessage); });
Advanced Example
This small example shows the mechanism of a Promise
. The testPromise()
method is called each time the <button>
is clicked. It creates a promise that will be fulfilled, using window.setTimeout()
, to the promise count (number starting from 1) every 1-3 seconds, at random. The Promise()
constructor is used to create the promise.
The fulfillment of the promise is simply logged, via a fulfill callback set using p1.then()
. A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise.
'use strict'; var promiseCount = 0; function testPromise() { let thisPromiseCount = ++promiseCount; let log = document.getElementById('log'); log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Started (<small>Sync code started</small>)<br/>'); // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s) let p1 = new Promise( // The resolver function is called with the ability to resolve or // reject the promise (resolve, reject) => { log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise started (<small>Async code started</small>)<br/>'); // This is only an example to create asynchronism window.setTimeout( function() { // We fulfill the promise ! resolve(thisPromiseCount); }, Math.random() * 2000 + 1000); } ); // We define what to do when the promise is resolved/rejected with the then() call, // and the catch() method defines what to do if the promise is rejected. p1.then( // Log the fulfillment value function(val) { log.insertAdjacentHTML('beforeend', val + ') Promise fulfilled (<small>Async code terminated</small>)<br/>'); }) .catch( // Log the rejection reason (reason) => { console.log('Handle rejected promise ('+reason+') here.'); }); log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise made (<small>Sync code terminated</small>)<br/>'); }
This example is started by clicking the button. You need a browser that supports Promise
. By clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another.
Loading an image with XHR
Another simple example using Promise
and XMLHttpRequest
to load an image is available at the MDN GitHub js-examples repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Promise' in that specification. |
Standard | Initial definition in an ECMA standard. |
ECMAScript Latest Draft (ECMA-262) The definition of 'Promise' in that specification. |
Draft |
Browser compatibility
To contribute to this compatibility data, please write a pull request against this repository: https://github.com/mdn/browser-compat-data.
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Promise() constructor | Chrome Full support 32 | Edge Full support 12 | Firefox
Full support
29
| IE No support No | Opera Full support 19 | Safari
Full support
8
| WebView Android Full support 4.4.3 | Chrome Android Full support 32 | Firefox Android
Full support
29
| Opera Android Full support Yes | Safari iOS
Full support
8
| Samsung Internet Android Full support 2.0 | nodejs
Full support
0.12
|
Legend
- Full support
- Full support
- No support
- No support
- See implementation notes.
- See implementation notes.
See also
- Using promises
- Promises/A+ specification
- Venkatraman.R - JS Promise (Part 1, Basics)
- Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)
- Jake Archibald: JavaScript Promises: There and Back Again
- Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript
- Matt Greer: JavaScript Promises ... In Wicked Detail
- Forbes Lindesay: promisejs.org
- Nolan Lawson: We have a problem with promises — Common mistakes with promises
- Promise polyfill
- Udacity: JavaScript Promises