[ES2024] Manually settle a promise using Promise.withResolvers

If we want to be able to modify the state of a promise from outside the constructor, we can use the Promise.withResolvers method to get access to the promise, and its resolve and reject functions.

 

// old approach
let res, rej;

const promise = new Promise((resolve, reject) => {
    res = resolve;
    rej = reject;
})

onClick(res)

 

// New approach

const { promise, resolve, reject } = Promise.withResolvers()

onClick(resolve)

 

posted @ 2024-05-22 14:28  Zhentiw  阅读(9)  评论(0编辑  收藏  举报