ECMAScript Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Open your command-line application and navigate to your workspace.
  2. Create a new folder named 3-04-chaining-promises.
  3. Copy or create an index.html that loads and runs a main function from main.js.
  1. Create a main.js file that creates a promise. Resolve a random number from the promise:
   new Promise(function (resolve) { 
     resolve(Math.random()); 
   }); 
);  
  1. Chain a then call off of the promise. Return true from the callback if the random value is greater than or equal to 0.5:
    new Promise(function (resolve, reject) { 
         resolve(Math.random()); 
   }).then(function(value) {
return value >= 0.5;
});
  1. Chain a final then call after the previous one. Log out a different message if the argument is true or false:
  new Promise(function (resolve, reject) { 
    resolve(Math.random()); 
  }).then(function (value) { 
    return value >= 0.5; 
  }).then(function (isReadyForLaunch) {
if (isReadyForLaunch) {
console.log('Start the countdown! ');
} else {
console.log('Abort the mission. ');
}
});
  1. Start your Python web server and open the following link in your browser: 
    http://localhost:8000/.

  2. If you are lucky, you'll see the following output:

  1. If you are unlucky, we'll see the following output: