1 function cook() { 2 console.log('開始做飯。'); 3 var p = new Promise(function (resolve, reject) { 4 setTimeout(function () { 5 console.log('做飯完畢!'); 6 re ...
1 function cook() { 2 console.log('開始做飯。'); 3 var p = new Promise(function (resolve, reject) { 4 setTimeout(function () { 5 console.log('做飯完畢!'); 6 resolve('雞蛋炒飯'); 7 }, 1000); 8 }); 9 return p; 10 } 11 12 function eat(data) { 13 console.log('開始吃飯:' + data); 14 var p = new Promise(function (resolve, reject) { 15 setTimeout(function () { 16 console.log('吃飯完畢!'); 17 resolve('一塊碗和一雙筷子'); 18 }, 2000); 19 }); 20 return p; 21 } 22 function wash(data) { 23 console.log('開始洗碗:' + data); 24 var p = new Promise(function (resolve, reject) { 25 setTimeout(function () { 26 console.log('洗碗完畢!'); 27 resolve('乾凈的碗筷'); 28 }, 2000); 29 }); 30 return p; 31 } 32 33 cook() 34 .then(eat) 35 .then(wash) 36 .then(function (data) { 37 console.log(data); 38 });
輸出:
備註:resolve只能傳入一個參數,傳入的其它參數,讀取到的值為"undefined"。