본문 바로가기

0/javascript

What is a Promise?

반응형

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});
 
promise1.then(function(value) {
  console.log(value);
  // expected output: "foo"
});
 
console.log(promise1);
// expected output: [object Promise]
 
cs


new Promise(executor);



executor


A function that is passed with the arguments resolve and reject. The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise, respectively. The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else rejects it if an error occurred. If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.


Description


A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.


A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options 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.



* 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 "locked in" to match the state of another promise.


Methods


Promise.all()

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 promise.


Promise.race()

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

Returns a Promise object that is rejected with the given reason.


Promise.resolve()

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 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 or onRejected 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.


To provide a function with promise functionality, simply have it return a promise:


1
2
3
4
5
6
7
8
9
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();
  });
}
cs


Examples


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-3seconds, 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.



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
'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/>');
 
    // 새 약속 생성
    var p1 = new Promise(
        function(resolve, reject){
            log.insertAdjacentHTML('beforeend', thisPromiseCount +
                ') Promise started (<small>Async code started</small>)<br/>');
 
            window.setTimeout(
                function(){
                    resolve(thisPromiseCount);
                }, Math.random()*2000+1000);
        }
    )
 
    p1.then(
        function(val){
            log.insertAdjacentHTML('beforeend', val    +
                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
        }
    )
    .catch(
        function(reason){
            console.log('Handle rejected promise('+reason+') here.');
        }
    );
 
    log.insertAdjacentHTML('beforeend', thisPromiseCount+
        ') Promise made(<small>Sync code terminated</small>)<br/>');
 
 
}
cs



출처 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise


반응형