3.1 Why Async Matters
The Problem: Some operations are slow:
- ๐ Reading files from disk
- ๐๏ธ Querying a database
- ๐ Fetching data from the internet
Node's Solution: Don't wait! Continue with other work.
Simple Example
// Node doesn't wait for slow operations
console.log("1. Start");
setTimeout(() => {
console.log("3. This runs after 1 second");
}, 1000);
console.log("2. This runs immediately");
// Output:
// 1. Start
// 2. This runs immediately
// 3. This runs after 1 second
3.2 Asynchronous Node.js APIs
Many Node.js operations are asynchronous by default. They don't block your code while waiting for results.
setTimeout()- Schedule code to run laterfs.readFile()- Read files from diskfs.writeFile()- Write files to diskfetch()- Make HTTP requestsDatabase queries- MongoDB, MySQL, PostgreSQL operationsNetwork operations- Sending/receiving data over the network
Why These Operations Are Asynchronous
These operations are slow compared to regular JavaScript code:
- ๐ File I/O - Reading/writing to disk takes milliseconds
- ๐๏ธ Database queries - Querying a database takes time
- ๐ Network requests - Fetching data from the internet can take seconds
If these were synchronous (blocking), your server would freeze!
Examples of Asynchronous Operations
// 1. setTimeout() - Schedule code to run later
console.log("Start");
setTimeout(() => {
console.log("This runs after 1 second");
}, 1000);
console.log("End");
// Output: Start, End, (1 second later) This runs after 1 second
// 2. fs.readFile() - Read file asynchronously
const fs = require('fs');
console.log("Before reading file");
fs.readFile('data.txt', 'utf8', (err, data) => {
// This callback runs AFTER the file is read
console.log("File content:", data);
});
console.log("After reading file (but file might not be read yet!)");
// 3. fetch() - Make HTTP request
console.log("Before fetch");
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// This runs AFTER the network request completes
console.log("Data received:", data);
});
console.log("After fetch (but request might not be done yet!)");
// 4. Database query (MongoDB example)
console.log("Before database query");
User.findById(userId)
.then(user => {
// This runs AFTER the database responds
console.log("User found:", user);
});
console.log("After database query (but query might not be done yet!)");
What Happens Behind the Scenes?
When you call an asynchronous function:
- โ Function starts - The operation begins (e.g., start reading file)
- โ Code continues - Your program doesn't wait, it moves to the next line
- โณ Operation runs in background - Node.js handles it while your code continues
- โ Callback/Promise fires - When done, your callback or Promise resolves
- Asynchronous operations don't block your code
- They run in the background while your code continues
- Results come back through callbacks or Promises
- This allows Node.js to handle many operations simultaneously
async/await!
3.3 Promises (Foundation of async/await) โ ๏ธ
async/await is just a cleaner way to write Promise code.
What is a Promise?
A Promise is an object representing a future value (success or failure).
Why do we need Promises? Remember those asynchronous operations we just learned about?
(fs.readFile, fetch, database queries, etc.)
Many of them return Promises to handle their results!
Think of it like ordering food at a restaurant:
- ๐งพ You place an order โ create a Promise
- โณ You wait for your food โ pending state
- โ Food arrives โ fulfilled (resolved)
- โ Order fails โ rejected
Real-World Connection: Async APIs Return Promises!
Many of the asynchronous operations we learned about return Promises:
// fs.promises.readFile() returns a Promise
const fs = require('fs').promises;
fs.readFile('data.txt', 'utf8')
.then(data => {
console.log('File content:', data); // โ
Success!
})
.catch(error => {
console.log('Error:', error); // โ Failure!
});
// fetch() returns a Promise
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log('Data:', data); // โ
Success!
})
.catch(error => {
console.log('Error:', error); // โ Failure!
});
// Database queries return Promises
User.findById(userId)
.then(user => {
console.log('User:', user); // โ
Success!
})
.catch(error => {
console.log('Error:', error); // โ Failure!
});
Creating Your Own Promise
// Creating a Promise manually
const myPromise = new Promise((resolve, reject) => {
// Simulate async operation (like database query)
setTimeout(() => {
const success = true;
if (success) {
resolve({ id: 1, name: 'Ahmad' }); // โ
Success!
} else {
reject('Something went wrong'); // โ Failure!
}
}, 1000);
});
// Using the Promise with .then() and .catch()
myPromise
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.log('Error:', error);
});
Understanding resolve and reject
They are callback functions provided by JavaScript when you create a Promise. You don't declare them - JavaScript gives them to you!
// โ resolve and reject are PROVIDED by JavaScript
const myPromise = new Promise((resolve, reject) => {
// You don't declare them - JavaScript gives them to you!
// You just CALL them when appropriate
});
Yes! You only declare the parameters you need:
// โ
Option 1: Only resolve (when errors are not possible)
new Promise((resolve) => {
setTimeout(() => {
resolve({ id: 1, name: 'John' }); // Always succeeds
}, 1000);
});
// โ
Option 2: Both resolve and reject (when errors are possible)
new Promise((resolve, reject) => {
if (userId > 0) {
resolve({ id: userId, name: 'John' });
} else {
reject(new Error('Invalid user ID')); // Can fail!
}
});
reject
because things can fail (network errors, database errors, etc.)
When to call each function:
| Function | When to Call | What Happens |
|---|---|---|
resolve(value) |
Operation succeeded | .then() receives the value |
reject(error) |
Operation failed | .catch() receives the error |
What Types Can resolve/reject Accept?
Both can accept ANY type of value:
// โ
resolve() can return ANY value type:
resolve("Success!"); // String
resolve(42); // Number
resolve(true); // Boolean
resolve({ id: 1, name: 'Ahmad' }); // Object
resolve([1, 2, 3]); // Array
// โ reject() can return ANY error type:
reject("Error message"); // String
reject(404); // Number (error code)
reject({ code: 500, message: "Failed" }); // Object
reject(new Error("Something went wrong")); // Error object (RECOMMENDED!)
new Error("message") with reject()
because it includes a stack trace for debugging!
How Does the Error Flow? (Complete Example)
// STEP 1: Create a function that returns a Promise
function getUser(userId) {
return new Promise((resolve, reject) => {
// STEP 2: Simulate database query
setTimeout(() => {
// STEP 3: Check if operation succeeded or failed
if (userId > 0) {
// SUCCESS: Call resolve() with the data
resolve({ id: userId, name: 'John' });
// This value goes to โ .then(user => ...)
} else {
// FAILURE: Call reject() with an error
reject(new Error('User ID must be positive'));
// This error goes to โ .catch(error => ...)
}
}, 1000);
});
}
Using with .then() and .catch()
// CASE 1: Success (userId = 1)
getUser(1)
.then(user => {
// โ
resolve() was called โ we get the user here
console.log(user); // { id: 1, name: 'John' }
})
.catch(error => {
// โ This is SKIPPED because resolve() was called
console.log(error.message);
});
// CASE 2: Failure (userId = -1)
getUser(-1)
.then(user => {
// โ This is SKIPPED because reject() was called
console.log(user);
})
.catch(error => {
// โ
reject() was called โ we get the error here
console.log(error.message); // "User ID must be positive"
});
Using with async/await
async function main() {
try {
// await waits for the Promise to resolve
const user = await getUser(1); // โ
Gets the resolved value
console.log(user);
} catch (error) {
// If reject() was called, the error comes here
console.log(error.message); // โ Gets the rejected error
}
}
resolveandrejectare provided by JavaScript, not declared by youresolve(value)- Call when successful โ goes to.then()reject(error)- Call when failed โ goes to.catch().then()- Handle success.catch()- Handle failure
3.4 async/await (Cleaner Promise Syntax) โญ
async/await is syntactic sugar for Promises - it makes Promise code look synchronous!
async- Put before a function (makes it return a Promise)await- Wait for the Promise result (only works inside async function)
Comparison: Promise vs async/await
// โ Using Promise .then() (harder to read)
getUser(1)
.then(user => {
console.log(user);
})
.catch(error => {
console.log(error);
});
// โ
Using async/await (much cleaner!)
async function main() {
try {
const user = await getUser(1);
console.log(user);
} catch (error) {
console.log(error);
}
}
Basic Example (Best Practice with Error Handling)
// This function returns a Promise (with proper error handling!)
function getUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) {
resolve({ id: id, name: 'John' });
} else {
reject(new Error('User ID must be positive'));
}
}, 1000);
});
}
// Using async/await with try/catch
async function main() {
try {
console.log("Getting user...");
const user = await getUser(1); // Wait for Promise to resolve
console.log("User:", user);
} catch (error) {
console.log("Error:", error.message);
}
}
main();
// Output (success):
// Getting user...
// (1 second later)
// User: { id: 1, name: 'John' }
3.5 Error Handling with try/catch
Always wrap await in try/catch to handle errors:
async function main() {
try {
const user = await getUser(1);
console.log("User:", user);
} catch (error) {
console.log("Error:", error.message);
}
}
3.6 The Express Pattern โญ
This is the pattern you'll use in ALL Express routes:
// Express route with async/await
app.get('/users/:id', async (req, res) => {
try {
// 1. Get ID from URL
const id = req.params.id;
// 2. Get data from database (await)
const user = await User.findById(id);
// 3. Send response
res.json(user);
} catch (error) {
// 4. Handle errors
res.status(500).json({ error: error.message });
}
});
More Examples
// GET all products
app.get('/products', async (req, res) => {
try {
const products = await Product.find();
res.json(products);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// POST create product
app.post('/products', async (req, res) => {
try {
const product = await Product.create(req.body);
res.status(201).json(product);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// DELETE product
app.delete('/products/:id', async (req, res) => {
try {
await Product.findByIdAndDelete(req.params.id);
res.json({ message: 'Deleted' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
- Node.js doesn't wait for slow operations
- Use
asyncbefore the function - Use
awaitto wait for data - Always use
try/catchfor error handling - Every Express route uses this pattern!
Quick Reference
// The pattern you'll use everywhere:
app.get('/endpoint', async (req, res) => {
try {
const data = await someAsyncOperation();
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});