aboutsummaryrefslogtreecommitdiff
path: root/files/id/web/javascript/reference/global_objects/promise/index.html
blob: 240915ba23f737136d4e1aeb2903832a25455b5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
---
title: Promise
slug: Web/JavaScript/Reference/Global_Objects/Promise
tags:
  - ECMAScript6
  - JavaScript
  - NeedsTranslation
  - Promise
  - TopicStub
translation_of: Web/JavaScript/Reference/Global_Objects/Promise
---
<div>{{JSRef}}</div>

<p>The <strong><code>Promise</code></strong> object is used for deferred and asynchronous computations. A <code>Promise</code> represents an operation that hasn't completed yet, but is expected in the future.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">new Promise( /* executor */ function(resolve, reject) { ... } );</pre>

<h3 id="Parameters">Parameters</h3>

<dl>
 <dt>executor</dt>
 <dd>A function that will be passed to other functions via the arguments <code>resolve</code> and <code>reject</code>. The <code>executor</code> function is executed immediately by the Promise implementation which provides the <code>resolve</code> and <code>reject</code> functions (the executor is called before the <code>Promise</code> constructor even returns the created object). The <code>resolve</code> and <code>reject</code> functions are bound to the promise and calling them fulfills or rejects the promise, respectively. The executor is expected to initiate some asynchronous work and then, once that completes, call either the <code>resolve</code> or <code>reject</code> function to resolve the promise's final value or else reject it if an error occurred.</dd>
</dl>

<h2 id="Description">Description</h2>

<p>A <code><strong>Promise</strong></code> 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 <em>promise</em> of having a value at some point in the future.</p>

<p>A <code>Promise</code> is in one of these states:</p>

<ul>
 <li><em>pending</em>: initial state, not fulfilled or rejected.</li>
 <li><em>fulfilled</em>: meaning that the operation completed successfully.</li>
 <li><em>rejected</em>: meaning that the operation failed.</li>
</ul>

<p>A pending promise can become either <em>fulfilled</em> with a value, or <em>rejected</em> with a reason (error). When either of these happens, the associated handlers queued up by a promise's <code>then</code> 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.)</p>

<p>As the <code>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> and <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}}</code> methods return promises, they can be chained—an operation called <em>composition</em>.</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png"></p>

<div class="note">
<p><strong>Note</strong>: A promise is said to be <em>settled </em>if it is either fulfilled or rejected, but not pending. You will also hear the term <em>resolved</em> used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's <a href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md">States and fates</a> contains more details about promise terminology.</p>
</div>

<h2 id="Properties">Properties</h2>

<dl>
 <dt><code>Promise.length</code></dt>
 <dd>Length property whose value is 1 (number of constructor arguments).</dd>
 <dt>{{jsxref("Promise.prototype")}}</dt>
 <dd>Represents the prototype for the <code>Promise</code> constructor.</dd>
</dl>

<h2 id="Methods">Methods</h2>

<dl>
 <dt>{{jsxref("Promise.all", "Promise.all(iterable)")}}</dt>
 <dd>Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises together.</dd>
 <dt>{{jsxref("Promise.race", "Promise.race(iterable)")}}</dt>
 <dd>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.</dd>
</dl>

<dl>
 <dt>{{jsxref("Promise.reject", "Promise.reject(reason)")}}</dt>
 <dd>Returns a <code>Promise</code> object that is rejected with the given reason.</dd>
</dl>

<dl>
 <dt>{{jsxref("Promise.resolve", "Promise.resolve(value)")}}</dt>
 <dd>Returns a <code>Promise</code> object that is resolved with the given value. If the value is a thenable (i.e. has a <code>then</code> 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 - {{jsxref("Promise.resolve", "Promise.resolve(value)")}} it instead and work with the return value as a promise.</dd>
</dl>

<h2 id="Promise_prototype"><code>Promise</code> prototype</h2>

<h3 id="Properties_2">Properties</h3>

<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}</p>

<h3 id="Methods_2">Methods</h3>

<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}</p>

<h2 id="Examples">Examples</h2>

<h3 id="Creating_a_Promise">Creating a Promise</h3>

<pre class="brush: html hidden">&lt;button id="btn"&gt;Make a promise!&lt;/button&gt;
&lt;div id="log"&gt;&lt;/div&gt;
</pre>

<p>This small example shows the mechanism of a <code>Promise</code>. The <code>testPromise()</code> method is called each time the {{HTMLElement("button")}} is clicked. It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the promise count (number starting from 1) every 1-3 seconds, at random. The <code>Promise()</code> constructor is used to create the promise.</p>

<p>The fulfillment of the promise is simply logged, via a fulfill callback set using {{jsxref("Promise.prototype.then()","p1.then()")}}. A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.</p>

<pre class="brush: js">'use strict';
var promiseCount = 0;

function testPromise() {
    var thisPromiseCount = ++promiseCount;

    var log = document.getElementById('log');
    log.insertAdjacentHTML('beforeend', thisPromiseCount +
        ') Started (&lt;small&gt;Sync code started&lt;/small&gt;)&lt;br/&gt;');

    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
    var p1 = new Promise(
        // The resolver function is called with the ability to resolve or
        // reject the promise
        function(resolve, reject) {
            log.insertAdjacentHTML('beforeend', thisPromiseCount +
                ') Promise started (&lt;small&gt;Async code started&lt;/small&gt;)&lt;br/&gt;');
            // 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/fulfilled 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 (&lt;small&gt;Async code terminated&lt;/small&gt;)&lt;br/&gt;');
        })
    .catch(
        // Log the rejection reason
        function(reason) {
            console.log('Handle rejected promise ('+reason+') here.');
        });

    log.insertAdjacentHTML('beforeend', thisPromiseCount +
        ') Promise made (&lt;small&gt;Sync code terminated&lt;/small&gt;)&lt;br/&gt;');
}</pre>

<pre class="brush:js hidden">if ("Promise" in window) {
  var btn = document.getElementById("btn");
   btn.addEventListener("click",testPromise);
}
else {
  log = document.getElementById('log');
  log.innerHTML = "Live example not available as your browser doesn't support the &lt;code&gt;Promise&lt;code&gt; interface.";
}
</pre>

<p>This example is executed when clicking the button. You need a browser supporting <code>Promise</code>. By clicking several times the button in a short amount of time, you'll even see the different promises being fulfilled one after the other.</p>

<p>{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}</p>

<h2 id="Example_using_new_XMLHttpRequest()">Example using new XMLHttpRequest()</h2>

<h3 id="Creating_a_Promise_2">Creating a Promise</h3>

<p>This example shows the implementation of a method which uses a <code>Promise</code> to report the success or failure of an {{domxref("XMLHttpRequest")}}.</p>

<pre class="brush: js">'use strict';

// A-&gt; $http function is implemented in order to follow the standard Adapter pattern
function $http(url){

  // A small example of object
  var core = {

    // Method that performs the ajax request
    ajax : function (method, url, args) {

      // Creating a promise
      var promise = new Promise( function (resolve, reject) {

        // Instantiates the XMLHttpRequest
        var client = new XMLHttpRequest();
        var uri = url;

        if (args &amp;&amp; (method === 'POST' || method === 'PUT')) {
          uri += '?';
          var argcount = 0;
          for (var key in args) {
            if (args.hasOwnProperty(key)) {
              if (argcount++) {
                uri += '&amp;';
              }
              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
            }
          }
        }

        client.open(method, uri);
        client.send();

        client.onload = function () {
          if (this.status &gt;= 200 &amp;&amp; this.status &lt; 300) {
            // Performs the function "resolve" when this.status is equal to 2xx
            resolve(this.response);
          } else {
            // Performs the function "reject" when this.status is different than 2xx
            reject(this.statusText);
          }
        };
        client.onerror = function () {
          reject(this.statusText);
        };
      });

      // Return the promise
      return promise;
    }
  };

  // Adapter pattern
  return {
    'get' : function(args) {
      return core.ajax('GET', url, args);
    },
    'post' : function(args) {
      return core.ajax('POST', url, args);
    },
    'put' : function(args) {
      return core.ajax('PUT', url, args);
    },
    'delete' : function(args) {
      return core.ajax('DELETE', url, args);
    }
  };
};
// End A

// B-&gt; Here you define its functions and its payload
var mdnAPI = 'https://developer.mozilla.org/en-US/search.json';
var payload = {
  'topic' : 'js',
  'q'     : 'Promise'
};

var callback = {
  success : function(data){
     console.log(1, 'success', JSON.parse(data));
  },
  error : function(data){
     console.log(2, 'error', JSON.parse(data));
  }
};
// End B

// Executes the method call
$http(mdnAPI)
  .get(payload)
  .then(callback.success)
  .catch(callback.error);

// Executes the method call but an alternative way (1) to handle Promise Reject case
$http(mdnAPI)
  .get(payload)
  .then(callback.success, callback.error);

// Executes the method call but an alternative way (2) to handle Promise Reject case
$http(mdnAPI)
  .get(payload)
  .then(callback.success)
  .then(undefined, callback.error);
</pre>

<h3 id="Loading_an_image_with_XHR">Loading an image with XHR</h3>

<p>Another simple example using <code>Promise</code> and <code><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> to load an image is available at the MDN GitHub<a href="https://github.com/mdn/promises-test/blob/gh-pages/index.html"> promise-test</a> repository. You can also <a href="http://mdn.github.io/promises-test/">see it in action</a>. Each step is commented and allows you to follow the Promise and XHR architecture closely.</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Initial definition in an ECMA standard.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p> </p>

<div>


<p>{{Compat("javascript.builtins.Promise")}}</p>
</div>

<p> </p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="http://promisesaplus.com/">Promises/A+ specification</a></li>
 <li><a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Jake Archibald: JavaScript Promises: There and Back Again</a></li>
 <li><a href="http://de.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript">Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript</a></li>
 <li><a href="http://www.mattgreer.org/articles/promises-in-wicked-detail/">Matt Greer: JavaScript Promises ... In Wicked Detail</a></li>
 <li><a href="https://www.promisejs.org/">Forbes Lindesay: promisejs.org</a></li>
 <li><a href="http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">Nolan Lawson: We have a problem with promises — Common mistakes with promises</a></li>
 <li><a href="https://github.com/jakearchibald/es6-promise/">Promise polyfill</a></li>
</ul>