Skip to content

Commit 6265289

Browse files
committed
add withResolvers
1 parent 0a1705c commit 6265289

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

apps/site/pages/en/learn/asynchronous-work/discover-promises-in-nodejs.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ Promise.resolve('Resolved immediately').then(result => {
261261
});
262262
```
263263

264-
### **`Promise.try()`**
264+
### **`Promise.try()`**:
265265

266266
`Promise.try()` is a method that executes a given function, whether it's synchronous or asynchronous, and wraps the result in a promise. If the function throws an error or returns a rejected promise, `Promise.try()` will return a rejected promise. If the function completes successfully, the returned promise will be fulfilled with its value.
267267

@@ -286,6 +286,24 @@ Promise.try(mightThrow)
286286

287287
In this example, `Promise.try()` ensures that if `mightThrow()` throws an error, it will be caught in the `.catch()` block, making it easier to handle both sync and async errors in one place.
288288

289+
### **`Promise.withResolvers()`**:
290+
291+
This method creates a new promise along with its associated resolve and reject functions, and returns them in a convenient object. This is used, for example, when you need to create a promise but resolve or reject it later from outside the executor function.
292+
293+
```js
294+
const { promise, resolve, reject } = Promise.withResolvers();
295+
296+
setTimeout(() => {
297+
resolve('Resolved successfully!');
298+
}, 1000);
299+
300+
promise.then(value => {
301+
console.log('Success:', value);
302+
});
303+
```
304+
305+
In this example, `Promise.withResolvers()` gives you full control over when and how the promise is resolved or rejected, without needing to define the executor function inline. This pattern is commonly used in event-driven programming, timeouts, or when integrating with non-promise-based APIs.
306+
289307
## Error Handling with Promises
290308

291309
Handling errors in Promises ensures your application behaves correctly in case of unexpected situations.
@@ -375,7 +393,7 @@ In short, the execution order is as follows:
375393
If a microtask queues another microtask, the new one is also executed before moving on.
376394
4. **Timers** (e.g., `setTimeout()`, `setInterval()`)
377395
5. **I/O callbacks** (e.g., network and file system operations)
378-
Some operations, like `close` events, may use `process.nextTick()` internally and are executed in the next tick.
396+
Some operations, like `close` and `error` events, may use `process.nextTick()` internally and are executed in the next tick.
379397
6. **`setImmediate()`** callbacks
380398

381399
`process.nextTick()` can execute at any stage in the execution order, as it is not bound by the event loop.

0 commit comments

Comments
 (0)