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-02-resolving-promise-results.
  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 and logs messages before and after the promise is created:
// main.js 
export function main () { 
 
  console.log('Before promise created'); 
 
  new Promise(function (resolve) { 
  }); 
 
  console.log('After promise created'); 
} 
  1. Within the promise, resolve a random number after a 5-second timeout:
    new Promise(function (resolve) { 
      setTimeout(function () {
resolve(Math.random());
}, 5000);
})
  1. Chain a then call off the promise. Pass a function that logs out the value of its only argument:
   new Promise(function (resolve) { 
      setTimeout(function () { 
        resolve(Math.random()); 
      }, 5000); 
    }).then(function (result) {
console.log('Long running job returned: %s', result);
});
  1. Start your Python web server and open the following link in your browser: 
    http://localhost:8000/.
  1. You should see the following output: