Skip to content

Latest commit

 

History

History
159 lines (134 loc) · 4.5 KB

2.9-ES6 Promises.md

File metadata and controls

159 lines (134 loc) · 4.5 KB

2.9-ES6 Promises ecma-international.org

ES6 standardise promises and remove the external dependencies currently required to use promises.

Promises and "Pyramid of Doom"

  1. A Promise can have one of these states: 1.1 Pending: initial state, not fulfilled or rejected. 1.2 Fulfilled: meaning that the operation completed successfully: fulfilled with a value 1.3 Rejected: meaning that the operation failed: rejected with a reason (error).

A Promise represents an operation that hasn't completed yet, but is expected to in the future.

A pending promise can become either fulfilled with a value, or rejected with a reason (error). As the Promise.prototype.then and Promise.prototype.catch methods return promises, they can be chained—an operation called composition.

alt text Source: developer.mozilla.org

New ES6 promises are created through the Promise constructor. This constructor accepts a single argument, which is a function (called the executor) containing the code to execute when the promise is added to the job queue. The executor is passed two functions as arguments, resolve() and reject(). The resolve() function is called when the executor has finished successfully in order to signal that the promise is ready to be resolved while the reject() function indicates that the executor has failed.

PARTS:

// Producing a promise As a producer, you create a promise and send a result via: states

// Consuming a promise As a consumer of promise, you are notified of a fulfillment or a rejection via reactions – callbacks that you register with the method then()

Promise ES5 Vs ES6 Pattern:

ES5 promise pattern

// Producing a promise
var deferred = $.defer();//x
doSomething(function cb(good) {
    if (good)
        deferred.resolve();//x
    else
        deferred.reject();//x
});
return deferred.promise; //x

// Consuming a promise (same)
promise.then(
      function (value) { /* fulfillment */ },
      function (reason) { /* rejection */ }
);

ES6 native Promise pattern

// Producing a promise
return new Promise(function(resolve, reject) {
    doSomething(function cb(good) {
        if (good)
            resolve();
        else
            reject();
    });
});
// Consuming a promise (same)
promise.then(
      function (value) { /* fulfillment */ },
      function (reason) { /* rejection */ }
);

===

ES6 native Promise pattern

// Defining: ES6 Promise Constructor
var promise = new Promise(function(resolve, reject) { // executor function with: resolve and reject function arguments
  if(true) {
    resolve("worked!");  
  } else {
    reject("didnt work");
  }
});

// Using: ES6 promise instance
promise
  .then(function(result){
    console.log(result);
  }, function(error){
    console.log(error);
  });

Ej1: Native Promises

ES6 Promises

// Defining Mock Data Service
var data;
function findData(){
  return new Promise(function (resolve, reject){
    if (data){
      resolve(data);
    }else{
      reject("data not found");
    }
  });
}

// Using Mock Data Service
promise
  .then(function(data){
    console.log(data);
  })
  catch(function(){
    console.log(error);
  })

ES6 Chaining Promises: Returning Values in Promise Chains

let foo = new Promise(function(resolve, reject) {
    return resolve(1);
});

foo.then(function(value) {		// value = 1 from executor 	
    console.log(value);         // "1"
    return value + 1;			// fulfillment handler returns 2	
}).then(function(value) {
    console.log(value);         // "2"
    return value + 1;			// fulfillment handler returns 3
}).then(function(value) {
    console.log(value);         // "3"
});

Eg: Chaining Promises

ES6 Chaining Promises + destructuring Values in Promise Chains

// Promizes change: Promise.all
var p10 = Promise.resolve([1,2]);
var p20 = Promise.resolve([3,4]);
var p30 = Promise.reject("FAIL"); // resolve this to trigger the chain

Promise.all([p10,p20,p30]).then(function([result1,result2,result3]){
  console.log(result1, result2);
  var [ A,B ] = result1;   // destructuring
  var [ C,D ] = result2;  // destructuring
  console.log(B); 
  console.log(D)
})
.catch(function(error){
  console.log(error + 'Error')
});

⬆ back to top