Introduction
JavaScript is asynchronous, meaning some operations (like API calls) take time to complete. Instead of blocking execution, JavaScript uses Promises to handle async tasks efficiently. To manage these Promises, we use then() and await to ensure smooth and structured execution of asynchronous operations.
1. Understanding then() (Promise Chaining)
The .then() method is used to handle the result of a Promise after it resolves. It allows method chaining, enabling multiple asynchronous operations to be executed in sequence.
Syntax:
promise.then(successCallback).catch(errorCallback);
Example:
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json()) // Convert response to JSON
.then((data) => console.log(data)) // Handle retrieved data
.catch((error) => console.error("Error:", error)); // Handle errors
When to Use then() ?
- When you prefer method chaining for handling Promises.
- When working with callback-based libraries like
fetch(). - When not using
async/await.
2. Understanding await (Inside Async Functions)
The await keyword pauses execution until a Promise resolves. It must be used inside an async function to ensure synchronous-looking code.
Syntax:
async function myFunction() {
let result = await somePromise;
}
Example:
async function fetchData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();
When to Use await?
- When you need cleaner, synchronous-looking async code.
- When handling multiple async calls in sequence.
- When inside an
asyncfunction.
3. then() vs await: A Side-by-Side Comparison
| Feature | then() |
await |
|---|---|---|
| Syntax Style | Callback-based | Synchronous-looking |
| Error Handling | .catch() |
try...catch |
| Readability | Can become hard to manage with deep .then() chains |
Cleaner and easier to follow |
| Usage Scope | Works anywhere | Only inside async functions |
4. Why Should You Use then() or await?
Using then() or await helps us:
- Handle async operations efficiently (e.g., API calls, database queries).
- Avoid callback hell (deeply nested callbacks that reduce readability).
- Write cleaner, structured, and more readable code.
- Ensure sequential execution when needed.
5. When to Choose then() or await?
Use then() when chaining simple Promises.
fetch("https://api.example.com/user")
.then((res) => res.json())
.then((user) => fetch(`https://api.example.com/posts/${user.id}`))
.then((res) => res.json())
.then((posts) => console.log(posts))
.catch((err) => console.error("Error:", err));
Use await when handling multiple async calls sequentially.
async function getUserPosts() {
try {
let resUser = await fetch("https://api.example.com/user");
let user = await resUser.json();
let resPosts = await fetch(`https://api.example.com/posts/${user.id}`);
let posts = await resPosts.json();
console.log(posts);
} catch (error) {
console.error("Error:", error);
}
}
getUserPosts();
6. Recommended Approach
For most cases, await is recommended due to its improved readability and ease of debugging. However, in scenarios where multiple independent Promises need to be resolved simultaneously, consider using Promise.all() with await:
async function fetchMultipleData() {
try {
let [user, posts] = await Promise.all([
fetch("https://api.example.com/user").then((res) => res.json()),
fetch("https://api.example.com/posts").then((res) => res.json()),
]);
console.log(user, posts);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchMultipleData();
Best Practices:
- Use
awaitfor sequential async tasks insideasyncfunctions. - Use
then()for method chaining or handling Promises outside async functions.
Summary:
- Use
awaitfor most async operations due to better readability. - Use
then()when method chaining is preferable. - Use
Promise.all()withawaitfor parallel async tasks to improve performance.
Top comments (0)