Get #Amazon #Prime for this #holiday #amazonprime #christmas #2019

#javascript #promise related examples

I would like to share some of my experience with javascript Promise. I will add on to this list when I have more promise examples to share.

Promise

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

A Promise has 3 states:
i) pending: initial state when a promise has not been fulfilled nor rejected yet.
ii) fulfilled: the operation within a promise is executed successfully.
iii) rejected: the operation within a promise failed to complete.

MDN Promise handling and chaining

Promise related examples

1) Wrapping functions that return a callback with a promise

// a function that takes a callback function
function foo(type, callback) {
  callback(type);
}

function fooPromise(param) {
    return new Promise(function(resolve, reject) {
         foo(param, (err, res) => {
             if (err !== null) 
               reject(err);
             resolve(res);
         });
    });
}


2) Returning a promise within a promise:

var innerPromise = function() {
  return new Promise(function(resolve, reject) {
    setTimeout(() => resolve("innerPromise fulfilled"), 1000);
  });
}

var outerPromise = function() {
  // return a promise that contains another promise
  return new Promise(function(resolve, reject) {
    // calling innerPromise
    innerPromise().then(function(res) {
       // innerPromise is done
       console.log(res);
       // resolve with some value / object 
       setTimeout(() => resolve("outerPromise fulfilled"), 1000);
    })
  });
}

outerPromise()
  .then(res => console.log(res))
  .catch(err => console.log(err)); 

// on console
// innerPromise fulfilled
// outerPromise fulfilled

I will keep updating this list. Thanks for reading!

Jun
Support me on Amazon