推荐答案
// www.javascriptcn.com code example
const { promise, resolve, reject } = Promise.withResolvers();
promise.then(value => {
console.log('Resolved with:', value);
}).catch(error => {
console.error('Rejected with:', error);
});
resolve('Success!');
// 或者
// reject('Error!');本题详细解读
什么是 Promise.withResolvers?
Promise.withResolvers 是一个静态方法,它返回一个包含 promise、resolve 和 reject 的对象。这个方法允许你在创建 Promise 的同时,获得对 resolve 和 reject 函数的引用,从而可以在稍后的代码中手动控制 Promise 的状态。
如何使用 Promise.withResolvers?
创建 Promise 和 Resolver:
- 调用
Promise.withResolvers()会返回一个对象,包含三个属性:promise: 一个待定的 Promise 对象。resolve: 一个函数,调用它可以将promise状态变为fulfilled,并传递一个值。reject: 一个函数,调用它可以将promise状态变为rejected,并传递一个错误。
- 调用
处理 Promise:
- 你可以像处理普通 Promise 一样,使用
.then()和.catch()来处理promise的结果。
- 你可以像处理普通 Promise 一样,使用
手动控制 Promise 状态:
- 在代码的适当位置,调用
resolve或reject来手动决定promise的状态。
- 在代码的适当位置,调用
示例代码解析
// www.javascriptcn.com code example
const { promise, resolve, reject } = Promise.withResolvers();
promise.then(value => {
console.log('Resolved with:', value);
}).catch(error => {
console.error('Rejected with:', error);
});
resolve('Success!');
// 或者
// reject('Error!');- 在这个示例中,
Promise.withResolvers()创建了一个promise对象,并返回了resolve和reject函数。 - 通过调用
resolve('Success!'),promise状态变为fulfilled,并且then回调会被触发,输出Resolved with: Success!。 - 如果调用
reject('Error!'),promise状态变为rejected,并且catch回调会被触发,输出Rejected with: Error!。
适用场景
- 当你需要在多个地方控制 Promise 的状态时,
Promise.withResolvers非常有用。 - 例如,在处理异步事件或需要在不同条件下手动决定 Promise 状态时,这种方法可以简化代码逻辑。