關鍵在於建立Promise物件的時候,需要對外暴露兩個引數。示例程式碼如下
var hook = {
resolve() {},
reject() {},
}
var myPromise = new Promise((res, rej) => {
hook.resolve = res;
hook.reject = rej;
})
myPromise.then(res => {
console.log('Resolved:', res);
}).catch(err => {
console.log('Rejected:', err);
})
之後簡單了,只需呼叫hook.resolve()
或者hook.reject()
就可以任意更改 promise 物件的狀態
本作品採用《CC 協議》,轉載必須註明作者和本文連結