ES6 – Promise

 · 4 mins read

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

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

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

Methods

  • 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.</p>

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

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

p.catch(onRejected)
//equals to 
p.then(undefined, onRejected) 
  • 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).

  • Promise.prototype.finally(onFinally)

    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.

let isLoading = true;

fetch(myRequest).then(function(response) {
    var contentType = response.headers.get("content-type");
    if(contentType && contentType.includes("application/json")) {
      return response.json();
    }
    throw new TypeError("Oops, we haven't got JSON!");
  })
  .then(function(json) { /* process your JSON further */ })
  .catch(function(error) { console.log(error); })
  .finally(function() { isLoading = false; });

A example of Promise.all

<br />function factory(name,milliseconds) {
    let p = new Promise(function (resolve, reject) {
        console.log(name + 'start')
        setTimeout(() => {
            console.log(name + 'done')
            resolve(name + 'resolved')
        }, milliseconds||1000);
    })
    return p
}

function start() {
    let p1 = factory("p1", 1000)
    let p2 = factory("p2", 2000)
    let p3 = factory("p3", 3000)

    p1.then(data => {
        console.log('fulfilled ' + data)
    })
    p2.then(data => {
        console.log('fulfilled ' + data)
    })
    p3.then(data => {
        console.log('fulfilled ' + data)
    })

    return [p1,p2,p3]
}

let promise_array = start()

Promise.all(promise_array).then((values)=>{
    console.log('promise all ' + values)
})

//  p1start
//  p2start
//  p3start
//  p1done
//  fulfilled p1resolved
//  p2done
//  fulfilled p2resolved
//  p3done
//  fulfilled p3resolved
//  promise all p1resolved, p2resolved, p3resolved


LINKS:

Promise