How to use promise
Jing, mqjing@gmail.com
GitHub: Download
'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
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function