Terjemahan ini belum lengkap. Mohon bantu menerjemahkan artikel ini dari Bahasa Inggris.

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.


new Promise( /* executor */ function(resolve, reject) { ... } );


A function that will be passed to other functions via the arguments resolve and reject. The executor function is executed immediately by the Promise implementation which provides the resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject 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 resolve or reject function to resolve the promise's final value or else reject it if an error occurred.


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 Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained—an operation called composition.

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 settled, or it is locked into a promise chain. Domenic Denicola's States and fates contains more details about promise terminology.


Length property whose value is 1 (number of constructor arguments).
Represents the prototype for the Promise constructor.


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.
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.
Returns a Promise object that is rejected with the given reason.
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then 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.

Promise prototype


Returns the function that created an instance's prototype. This is the Promise function by default.


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(onFulfilled, onRejected)
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 or onRejected is not a function).
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

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 resolve, 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 shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.

'use strict';
var promiseCount = 0;

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

    var 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)
    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 (<small>Async code started</small>)<br/>');
            // This is only an example to create asynchronism
                function() {
                    // We fulfill the promise !
                }, 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.
        // Log the fulfillment value
        function(val) {
            log.insertAdjacentHTML('beforeend', val +
                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
        // Log the rejection reason
        function(reason) {
            console.log('Handle rejected promise ('+reason+') here.');

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

This example is executed when clicking the button. You need a browser supporting Promise. 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.

Example using new XMLHttpRequest()

Creating a Promise

This example shows the implementation of a method which uses a Promise to report the success or failure of an XMLHttpRequest.

'use strict';

// A-> $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 && (method === 'POST' || method === 'PUT')) {
          uri += '?';
          var argcount = 0;
          for (var key in args) {
            if (args.hasOwnProperty(key)) {
              if (argcount++) {
                uri += '&';
              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);

        client.open(method, uri);

        client.onload = function () {
          if (this.status >= 200 && this.status < 300) {
            // Performs the function "resolve" when this.status is equal to 2xx
          } else {
            // Performs the function "reject" when this.status is different than 2xx
        client.onerror = function () {

      // 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-> 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 

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

// Executes the method call but an alternative way (2) to handle Promise Reject case 
  .then(undefined, callback.error);

Loading an image with XHR

Another simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.


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.

Browser compatibility


FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support32 Yes29 No198
Promise() constructor32 Yes291 No1983
all32 Yes29 No198
prototype32 Yes29 No198
catch32 Yes29 No198
finally63 No58 No5011.1
then32 Yes29 No198
race32 Yes29 No198
reject32 Yes29 No198
resolve32 Yes29 No198
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support4.4.432 Yes29 Yes8 Yes
Promise() constructor4.4.432 Yes291 Yes83 Yes
all4.4.432 Yes29 Yes8 Yes
prototype4.4.432 Yes29 Yes8 Yes
catch4.4.432 Yes29 Yes8 Yes
finally6363 No585011.1 No
then4.4.432 Yes29 Yes8 Yes
race4.4.432 Yes29 Yes8 Yes
reject4.4.432 Yes29 Yes8 Yes
resolve4.4.432 Yes29 Yes8 Yes

1. Constructor requires a new operator since version 37.

2. Constructor requires a new operator since version 4.

3. Constructor requires a new operator since version 10.


See also

Tag Dokumen dan Kontributor

Kontributor untuk laman ini: fscholz, PeteDevoy
Terakhir diperbarui oleh: fscholz,