Skip to content

Commit 35d7a18

Browse files
fix: setImmediate docs
1 parent 0b24039 commit 35d7a18

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -367,21 +367,31 @@ console.log('Synchronous task executed');
367367

368368
### `setImmediate()`
369369

370-
`setImmediate()` is used to execute a callback after the current event loop cycle finishes and all I/O events have been processed. This means that `setImmediate()` callbacks run after any I/O callbacks, but before timers.
370+
`setImmediate()` schedules its callback for the event loop’s check phase—i.e. it will run immediately after all of the current loop’s I/O callbacks (poll phase) have completed.
371371

372372
```js
373+
const fs = require('fs');
374+
373375
setImmediate(() => {
374376
console.log('Immediate callback');
375377
});
376378

379+
fs.readFile('./some.txt', () => {
380+
console.log('I/O callback (file read)');
381+
});
382+
383+
setTimeout(() => {
384+
console.log('Timeout callback')
385+
}, 0)
386+
377387
console.log('Synchronous task executed');
378388
```
379389

380390
### When to Use Each
381391

382392
- Use `queueMicrotask()` for tasks that need to run immediately after the current script and before any I/O or timer callbacks, typically for Promise resolutions.
383393
- Use `process.nextTick()` for tasks that should execute before any I/O events, often useful for deferring operations or handling errors synchronously.
384-
- Use `setImmediate()` for tasks that should run after I/O events but before timers.
394+
Use `setImmediate()` for tasks that should run after the current event loop’s I/O events, but before timers scheduled for the next loop iteration.
385395

386396
Because these tasks execute outside of the current synchronous flow, uncaught exceptions inside these callbacks won't be caught by surrounding `try/catch` blocks and may crash the application if not properly managed (e.g., by attaching `.catch()` to Promises or using global error handlers like `process.on('uncaughtException')`).
387397

0 commit comments

Comments
 (0)