es6 promise control flow in series

This snippet uses the new build in feature promise in es6. The promise doubles the number and returns the doubled value in the resolve callback. When the resolve is called, then the “then” is executed with the value being passed from the resolve callback. Each then is called in the order it is written.

// double the num after a timeout of 3 or less seconds
// resolve with the doubled value
function doubleSizeAfterTimeout (num) {
    var timeout = Math.random() * 3000;
    return new Promise(function (resolve, reject) {
        function doDouble() {
          resolve(num * 2);
        }
        setTimeout(doDouble, timeout);
    });
}

// Calling the promise function doubleSizeAfterTimeout
// each function in the then takes the doubled value from the previous resolved value
console.log("2 (The initial number)");
doubleSizeAfterTimeout(2)
.then(
  function (num) { 
    console.log(num + " (The result of the first promise.)");
    return doubleSizeAfterTimeout(num); 
  }
)
.then(
  function (num) { 
    console.log(num + " (The result of the second promise.)");
    return doubleSizeAfterTimeout(num); 
  }
)
.then(
  function (num) { 
    console.log(num + " (The final number)"); 
  }
);

// 2 (The initial number)
// 4 (The result of the first promise.)
// 8 (The result of the second promise.)
// 16 (The final number)

Search within Codexpedia

Custom Search

Search the entire web

Custom Search