NodeJS Notes 01
NodeJS Notes 01
A JavaScript function that schedules code to run after a specified delay (in milliseconds).
Part of the Web API (browser) or Node.js timers module, not the JavaScript language
itself.
Non-blocking: allows other code to run while waiting for the delay.
Syntax:
setTimeout(callback, delay, ...args);
Output:
Start
End
[after ~2s]
Delayed by 2 seconds
setTimeout pushes the callback to the task queue after the delay, executed only when
the call stack is empty.
Key Points:
Delay is not guaranteed (minimum delay, depends on event loop).
Use clearTimeout(timeoutId) to cancel a scheduled setTimeout.
Useful for delays, animations, or scheduling tasks.
Consuming a Promise:
Use .then for success and .catch for errors:
myPromise
.then(result => console.log(result)) // 'Success!'
.catch(error => console.error(error));
Key Points:
resolve(value): Marks promise as fulfilled, passes value to .then.
reject(reason): Marks promise as rejected, passes reason to .catch.
Promises are ideal for I/O operations (e.g., fetching data, reading files).
Always include error handling to avoid uncaught rejections.
fetchData()
.then(result => {
console.log(result); // 'Done!'
return fetchData(); // Returns new promise
})
.then(result2 => {
console.log(result2); // 'Done!' (after another 1500ms)
})
.catch(error => console.error('Error:', error));
Output:
Done!
[after ~1500ms]
Done!
Key Points:
Return a value or promise in .then to pass it to the next .then.
Chain breaks if a .then doesn’t return a value/promise (returns undefined).
Use .catch at the end to handle errors from any promise in the chain.
Alternative: Use async/await for cleaner sequential async code:
async function run() {
try {
const result = await fetchData();
console.log(result);
const result2 = await fetchData();
console.log(result2);
} catch (error) {
console.error('Error:', error);
}
}
run();
Output:
Start
End
Promise
Timeout
Explanation:
1. Start and End run synchronously (call stack).
2. Promise runs next (microtask queue, high priority).
3. Timeout runs last (task queue, lower priority).
Key Points:
Synchronous code runs first.
Promises (microtasks) execute before timers (macrotasks).
Use tools like console.log or debuggers to trace execution order.
Understanding order prevents issues like race conditions or accessing unresolved data.
Additional Tips
Debugging Async Code:
Use async/await for readable sequential code.
Log timestamps or use debuggers to track timing.
Test edge cases (e.g., promise rejections, network failures).
Best Practices:
Always handle errors with .catch or try/catch.
Avoid nesting .then (use chaining or async/await).
Use Promise.all for parallel async tasks.
Resources:
MDN Web Docs: Promises, setTimeout, Event Loop.
JavaScript.info: Async/await, Event Loop.
Book: You Don’t Know JS (Async & Performance).
Node.js Core Modules and Their Usage
• Usage Context: Core modules are built into Node.js and don’t require installation (e.g.,
require('fs')). They cover essential functionality for server-side development.
• Async Support: Many modules (e.g., fs, crypto) offer both synchronous and asynchronous
methods. Prefer async methods (e.g., fs.promises) for non-blocking I/O.
• Modern Alternatives: Some modules (e.g., url, querystring) are less common with
modern APIs like new URL() or third-party libraries, but they remain useful for legacy code.
• Documentation: Refer to the Node.js Documentation for detailed APIs and examples.
• Example Workflow:
const fs = require('fs').promises;
const http = require('http');
const path = require('path');
• Uses fs for file reading, path for path handling, and http for a web server.