2017年10月2日 星期一

JavaScript Promise 簡單範例說明

範例:
// new 一個 Promise 需要一個 callback, 這個 callback 可接受兩個 callback
var promiseToCleanTheRoom = new Promise(function (resolve, reject) {
console.log('promise is working');
let isClean = true;
if (isClean) {
resolve('clean'); // 執行 .then() 的 callback
} else {
reject('not clean'); // 執行 .catch() 的 callback
}
});
promiseToCleanTheRoom.then(function (fromResolve) {
// resolve
console.log('room is ' + fromResolve);
}).catch(function (fromReject) {
// reject
console.log('room is ' + fromReject);
});

必須完成某件事才能進行下一件事
例如 "打掃房間 > 丟垃圾 > 拿到冰淇淋"
let cleanRoom = function () {
return new Promise(function (resolve, reject) {
resolve(' Cleaned the room.');
});
};

let removeGarbage = function (p) {
return new Promise(function (resolve, reject) {
resolve(p + ' Remove garbage.');
});
};

let winIceCream = function (p) {
return new Promise(function (resolve, reject) {
resolve(p + ' won ice cream!');
});
};
cleanRoom().then(function (result) { // 等待 cleanRoom 的結果
return removeGarbage(result);
}).then(function (result) { // 等待 removeGarbage 的 結果
return winIceCream(result);
}).then(function (result) { // 等待 winIceCream 的結果
console.log('finished : ' + result);
});

三個 Promise 同時進行,等待全部完成:
Promise.all([cleanRoom(), removeGarbage(), winIceCream()]).then(function () {
console.log('all done');
});

只少有一個 Promise 已經先完成:
Promise.race([cleanRoom(), removeGarbage(), winIceCream()]).then(function () {
console.log('one of them is done');
});