Promise

공헌자 숫자: 1명

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

This is a new technology, part of the ECMAScript 2015 (ES6) standard .
This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.

Promise 객체는 지연 및 비동기 연산을 위해 사용됩니다. 프로미스(Promise) 인스턴스는 다음 중 하나의 상태를 가집니다:

  • 대기(pending): 충족도, 파투도 이루어지지 않은, 초기상태.
  • 충족(fulfilled): 연산성공.
  • 파투(rejected): 연산실패.
  • 정체(settled): 아직 약속이 충족되지도, 파투나지도 않았지만, 대기상태는 아닌 상태.

Syntax

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

Parameters

executor
resolvereject를 인자로 받는 함수 객체입니다. 첫번째 인자는 프로미스를 만족시키고, 두번째 인자는 거부시킵니다. 처리하고자 하는 연산이 완료되었을 때 이러한 함수들을 호출하면 됩니다.

Description

Promise 인터페이스는 프로미스가 생성된 순간에는 알 필요가 없는 값에 대한 프록시라고 보면 됩니다: 비동기 액션이 성공하거나 실패한 순간에 작동하는 핸들러를 연결할 수 있습니다. 프로미스의 이러한 특징 덕분에, 비동기 메서드에서도 동기 메서드인 것처럼 값을 곧바로 반환할 수 있게 됩니다. 최종 결과를 반환하는 대신, 미래에 존재하게 될 어떤 값에 대한 약속을 반환하는 겁니다.

대기중인 프로미스는 곧 약속을 충족시킬 수도, 무슨 일이 생겨서 파투를 내버릴 수도 있습니다. 그런 사건이 발생하게 되면 프로미스의 then 메서드에 의해 대기중이던 관련 핸들러가 호출됩니다. (만약 핸들러가 연결되기도 전에 약속이 지켜졌거나 파투났다면, 핸들러는 곧바로 호출될 겁니다. 따라서 경합조건(race condition)이 발생하지 않습니다.)

As the Promise.prototype.then and Promise.prototype.catch methods return promises, they can be chained—an operation called composition.

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.
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 a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

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(onRejected)
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.

Examples

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 string "result" every 1-3 seconds, at random.

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 the string 'result' (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 only is 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 fulfilled
    //but we only call this if the promise is resolved/fulfilled
    p1.then(
        // Just log the message and a value
        function(val) {
            log.insertAdjacentHTML('beforeend', val +
                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
        }).catch(function() { console.log('promise was rejected');});

    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 promise 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.send();

        client.onload = function () {
          if (this.status == 200) {
            // Performs the function "resolve" when this.status is equal to 200
            resolve(this.response);
          } else {
            // Performs the function "reject" when this.status is different than 200
            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-> 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);

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.

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Promise' in that specification.
Standard Initial definition in an ECMA standard.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 32.0 24.0 (24.0) as Future
25.0 (25.0) as Promise behind a flag[1]
29.0 (29.0) by default
12/Edge (Modern.IE status) 19 7.1
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support Not supported 32.0 24.0 (24.0) as Future
25.0 (25.0) as Promise behind a flag[1]
29.0 (29.0) by default
Not supported Not supported iOS 8 32.0

[1] Gecko 24 has an experimental implementation of Promise, under the initial name of Future. It was renamed to its final name in Gecko 25, but disabled by default behind the flag dom.promise.enabled. Bug 918806 enabled Promises by default in Gecko 29.

See also

문서 태그 및 공헌자

Contributors to this page: 0xABCDEF
최종 변경: 0xABCDEF,
사이드바 숨기기