javascript / intermediate
Snippet
Manual Promise Control with withResolvers
Promise.withResolvers() is a modern standard (Node.js 22+) that provides a cleaner way to create a promise and its controllers simultaneously, avoiding the need to nest logic inside the Promise constructor callback.
snippet.js
1
2
3
4
5
6
7
8
9
const { promise, resolve, reject } = Promise.withResolvers();// Useful for complex event-based logicsetTimeout(() => {const success = Math.random() > 0.5;success ? resolve('Task Done!') : reject(new Error('Failed'));}, 1000);const result = await promise;
nodejs
Breakdown
1
const { promise, resolve, reject } = Promise.withResolvers();
Destructures the three components needed to manage an asynchronous operation manually.