es6 promise resolve and reject example

This es6 promise code snippet demonstrates the use of resolve and reject with Promise. When constructing a Promise, it takes two callback functions as arguments. The first one for success callback and the second one for fail or error callback. The name can be whatever you like but by convention, it is usually resolve for success and reject for error.

console.log("Started (Sync code started)");
// a promise that will return the status in string after waiting 3 or less seconds
function myPromise(random) { 
  return new Promise(
    function(resolve, reject) {       
      console.log('Promise started (Async code started)');
      function decideStatus() {
        // resolve with the status fulfilled if the random number is greater than 0.5 
        // otherwise reject with the status rejected
        (random > 0.5) ? resolve("fulfilled"):reject("rejected");
      }
      setTimeout(decideStatus, random * 3000);
    });
}

// then on resolve
// catch on reject
myPromise(Math.random())
.then(
  function(status) {
    console.log('Promise ' + status + ' (Async code terminated)');
})
.catch(
  function(status) {
    console.log('Promise ' + status + ' (Async code terminated)');
});
console.log('Promise made (Sync code terminated)');

// Started (Sync code started)
// Promise started (Async code started)
// Promise made (Sync code terminated)
// Promise rejected (Async code terminated)

Search within Codexpedia

Custom Search

Search the entire web

Custom Search