让 Promise 的状态变成可控的

JavaScript/前端
366
0
0
2022-04-12

让 Promise 的状态变成可控的

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