2016年11月29日 星期二

[nodejs, async, promise] 最簡單的方式使用 promise

How to use promise
GitHub: Download
(This picture was taken from here)
Google doc: This document.
'use strict';

// 定義一個高耗時非同步 function: c 毫秒後, 才會 resolving 輸入的 x
function LongTimeTask(x, c) {

 // 高耗時非同步工作
 return new Promise(resolve => {
   setTimeout(() => {
     resolve(x);
   }, c);
 });
}



function main() {
 // Step 1: Run the first LongTimeTask which takes 4 seconds
 let xPromise1 = LongTimeTask("First", 4000);
 xPromise1.then(function (x) {
    // 四秒後, 才會執行到這裡
    console.log(x);
 });

 // Step 2: Run the second LongTimeTask whick takes 2 seconds
 let xPromise2 = LongTimeTask("Second", 1000);
 xPromise2.then(function (x) {
    // 一秒鐘後, 就會執行到這裡
    console.log(x);
 });

 // Step 3: 希望先執行 Third_1 task, 然後才是 Third_2 Task
 //               在這裡使用巢狀的執行
 let xPromise3 = LongTimeTask("Third_1", 4000);
 xPromise3.then(function (x) {
    // 四秒鐘, 會執行到這裡
    console.log(x);
   return LongTimeTask("Thrid_2", 2000);
 }).then( v => {
    // 當 Third_1 執行完成後, 再執行這裡
    console.log(v);
 });
}


main();






References

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function