Nodejs異步編程之Promises chaining

1. 案例一

1.1. 案例描述

resolve()函數的輸入參數:無
用戶函數函數的返回值:無
函數書寫形式:完整
Promise: ×1
chain: ×1

1.2. 源代碼 “case1.js”
let promise = new Promise(
    function(resolve, reject){
        console.log('Initialize a Promise to Complete Five Things Sequentially 1 -> 2 -> 3 -> 4 -> 5 as follows:');
        resolve();
    }
);

promise.then(
    function(){
        console.log("Thing 1");
    }
).then(
    function(){
        console.log("Thing 2");
    }
).then(
    function(){
        console.log("Thing 3");
    }
).then(
    function(){
        console.log("Thing 4");
    }
).then(
    function(){
        console.log("Thing 5");
    }
)
1.3. 運行結果
$ node case1.js
Initialize a Promise to Complete Five Things Sequentially 1 -> 2 -> 3 -> 4 -> 5 as follows:
Thing 1
Thing 2
Thing 3
Thing 4
Thing 5

2. 案例二

2.1. 案例描述

resolve()函數的輸入參數:無
用戶函數函數的返回值:有
函數書寫形式:完整
Promise: ×1
chain: ×1

2.2. 源代碼 “case2.js”
let promise = new Promise(
    function(resolve, reject){
        console.log('Initialize a Promise to Complete Five Things Sequentially 1 -> 2 -> 3 -> 4 -> 5 as follows:');
        resolve();
    }
);

promise.then(
    function(){
        var value=1;
        console.log("Thing 1, value: ", value);
        return value;
    }
).then(
    function(value){
        value = value + 1;
        console.log("Thing 2, value: ", value);
        return value;
    }
).then(
    function(value){
        value = value + 1;
        console.log("Thing 3, value: ", value);
        return value;
    }
).then(
    function(value){
        value = value + 1;
        console.log("Thing 4, value: ", value);
        return value;
    }
).then(
    function(value){
        value = value + 1;
        console.log("Thing 5, value: ", value);
        return value;
    }
)
2.3. 運行結果
$ node case2.js
Initialize a Promise to Complete Five Things Sequentially 1 -> 2 -> 3 -> 4 -> 5 as follows:
Thing 1, value:  1
Thing 2, value:  2
Thing 3, value:  3
Thing 4, value:  4
Thing 5, value:  5


其他

案例描述

resolve()函數的輸入參數:無
用戶函數函數的返回值:無
函數書寫形式:簡化
Promise: ×1
chain: ×1

源代碼 “case.js”
let promise = new Promise(
    (resolve, reject) => {
        console.log('Initialize a Promise to Complete Five Things Sequentially 1 -> 2 -> 3 -> 4 -> 5 as follows:');
        resolve();
    }
);

promise.then(
    () => {
        console.log('Thing 1');;
    }
).then(
    () => {
        console.log('Thing 2')
    }
).then(
    () => {
    console.log('Thing 3')
    }
).then(
    () => {
    console.log('Thing 4')
    }
).then(
    () => {
    console.log('Thing 5')
    }
)
運行結果
$ node case.js
Initialize a Promise to Complete Five Things Sequentially 1 -> 2 -> 3 -> 4 -> 5 as follows:
Thing 1
Thing 2
Thing 3
Thing 4
Thing 5
發佈了395 篇原創文章 · 獲贊 91 · 訪問量 49萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章