0% found this document useful (0 votes)
0 views

NodeJS Notes 01

The document provides a comprehensive overview of asynchronous JavaScript, covering key concepts such as setTimeout, promises, and the event loop. It explains how to create and consume promises, chain them for sequential operations, and emphasizes the importance of understanding execution order in asynchronous tasks. Additionally, it lists Node.js core modules, their descriptions, common usage, and best practices for handling asynchronous code.

Uploaded by

Nazia Syed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

NodeJS Notes 01

The document provides a comprehensive overview of asynchronous JavaScript, covering key concepts such as setTimeout, promises, and the event loop. It explains how to create and consume promises, chain them for sequential operations, and emphasizes the importance of understanding execution order in asynchronous tasks. Additionally, it lists Node.js core modules, their descriptions, common usage, and best practices for handling asynchronous code.

Uploaded by

Nazia Syed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Asynchronous JavaScript Study Notes

1. Using setTimeout for Delayed Execution


 What is setTimeout?

 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);

 callback: Function to execute after delay milliseconds.


 delay: Time to wait (in ms).
 ...args: Optional arguments passed to the callback.
 Example:
console.log('Start');
setTimeout(() => {
console.log('Delayed by 2 seconds');
}, 2000);
console.log('End');

 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.

2. Creating and Resolving Promises for Asynchronous Tasks


 What is a Promise?
 An object representing the eventual completion (or failure) of an asynchronous
operation.
 States: pending, fulfilled (resolved), or rejected.
 Simplifies handling async tasks compared to callbacks.
 Creating a Promise:
const myPromise = new Promise((resolve, reject) => {
// Async task (e.g., timer, API call)
setTimeout(() => {
resolve('Success!'); // Resolves with a value
// or reject('Error!'); // Rejects with a reason
}, 1000);
});

 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.

3. Chaining Promises for Sequential Asynchronous Operations


 What is Promise Chaining?
 Linking multiple .then calls to run async operations in sequence.
 Each .then returns a new promise, allowing further chaining.
 Example:
const fetchData = () => new Promise(resolve => {
setTimeout(() => resolve('Done!'), 1500);
});

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();

4. Importance of Understanding Execution Order in


Asynchronous JavaScript
 Why Execution Order Matters:
 JavaScript is single-threaded with an event loop, processing tasks asynchronously.
 Async operations (timers, promises, API calls) don’t block the main thread, leading to
non-linear execution.
 Misunderstanding order can cause bugs (e.g., accessing data before it’s available).
 How the Event Loop Works:
 Call Stack: Executes synchronous code.
 Task Queue: Holds callbacks from timers, I/O, etc.
 Microtask Queue: Holds promise callbacks (higher priority than task queue).
 Event Loop: Moves tasks/microtasks to the stack when it’s empty.
 Example:
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');

 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

Module Description Common Usage


Provides assertion testing for Writing unit tests; validating conditions (e.g.,
assert
debugging and testing. assert.strictEqual(a, b)).
buffer Handles binary data directly Manipulating binary data, such as
(e.g., raw memory buffers). reading/writing files or handling streams.
Running external commands (e.g., exec,
child_process Spawns child processes to run
shell commands or scripts. spawn for scripts or CLI tools).
cluster Enables multi-core processing Scaling apps across CPU cores for better
by forking worker processes. performance (e.g., web servers).
Provides cryptographic Hashing passwords (e.g.,
crypto functions (hashing, encryption, crypto.createHash('sha256')),
etc.). generating tokens.
Resolving domain names (e.g.,
Performs DNS lookups and
dns dns.lookup('example.com')) or custom
name resolution.
DNS queries.
Module Description Common Usage
Implements the EventEmitter
Creating custom event listeners/emitters (e.g.,
events class for event-driven
emitter.on('event', callback)).
programming.
Interacts with the file system File operations (e.g., fs.readFile,
fs (reading, writing, deleting files,
fs.writeFile, fs.mkdir).
etc.).
Creates HTTP servers and Building web servers (e.g.,
http clients for handling web http.createServer) or making HTTP
requests. requests.
Like http, but for secure
Creating secure web servers or clients (e.g.,
https HTTPS communication using https.get).
TLS/SSL.
Creates TCP servers and clients Building TCP-based apps (e.g., chat servers,
net
for low-level networking. net.createServer).
Provides operating system- Accessing system info (e.g., os.cpus(),
os related utility methods and
os.platform(), os.totalmem()).
properties.
Handles file paths and Manipulating file paths (e.g., path.join(),
path directories in a platform-
path.resolve(), path.extname()).
agnostic way.
Parses and formats URL query Handling query parameters (e.g.,
querystring
strings. querystring.parse('key=value')).
readline Reads input streams (e.g., stdin) Creating CLI interfaces (e.g., prompting user
line by line. input from terminal).
Provides an API for handling Processing large data efficiently (e.g.,
stream
streaming data. fs.createReadStream, piping streams).
Implements timers like
Scheduling tasks (e.g.,
timers setTimeout and
setTimeout(callback, delay)).
setInterval.
URL manipulation (e.g.,
url Parses and formats URLs. url.parse('http://example.com'),
new URL()).
Debugging (e.g., util.inspect),
util Provides utility functions (e.g.,
promisifying callbacks (e.g.,
formatting, promisifying).
util.promisify).
Provides
Compressing data (e.g., zlib.gzip) for HTTP
zlib compression/decompression
responses or file storage.
functionality (e.g., gzip).
Notes

• 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');

http.createServer(async (req, res) => {


const filePath = path.join(__dirname, 'index.html');
try {
const data = await fs.readFile(filePath);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
} catch (error) {
res.writeHead(500);
res.end('Error');
}
}).listen(3000);

• Uses fs for file reading, path for path handling, and http for a web server.

You might also like