关键在于创建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 对象的状态