Chapter 6: Promises and Async/Await
Welcome back to "Mastering JavaScript"! In Chapter 5, we delved into advanced array methods and object manipulation. Today, we'll take a look at asynchronous programming in JavaScript, focusing on Promises and async/await
syntax. These concepts can initially seem tricky, but with a bit of practice, you'll be handling asynchronous operations like a pro!
6.1 Introduction to Asynchronous Programming
In JavaScript, many operations, like fetching data from a server, are asynchronous. This means that the code execution doesn't wait for these operations to complete. Instead, it continues running, and the asynchronous operations are handled separately, allowing for a smoother and more efficient program.
6.2 Understanding Promises
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises have three states:
Pending: The initial state, neither fulfilled nor rejected.
Fulfilled: The operation completed successfully.
Rejected: The operation failed.
Here's a simple example of a Promise:
let promise = new Promise((resolve, reject) => {
let success = true; // Change this to false to see how rejection works
setTimeout(() => {
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed!");
}
}, 2000);
});
promise.then((message) => {
console.log(message); // Output: "Operation was successful!" (after 2 seconds)
}).catch((error) => {
console.log(error); // Output: "Operation failed!" (if success was false)
});
In this example, we create a new Promise that either resolves (succeeds) or rejects (fails) after 2 seconds, depending on the success
variable.
6.3 Usingasync
andawait
The async
and await
keywords provide a more readable and straightforward way to work with Promises.
async
: When you declare a function asasync
, it means the function will return a Promise.await
: Theawait
keyword can be used insideasync
functions to pause the execution of the function until the Promise is resolved or rejected.
Here's a simple example:
async function fetchData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchData();
In this example, fetchData
is an async
function that fetches data from an API. The await
keyword is used to wait for the Promise returned by fetch
to resolve, and then for the Promise returned by response.json()
to resolve.
6.4 Practical Examples
Let's see some practical examples to solidify these concepts.
Example 1: Chaining Promises
let promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve(10), 1000);
});
promise1.then((result) => {
console.log(result); // Output: 10
return result * 2;
}).then((result) => {
console.log(result); // Output: 20
return result * 3;
}).then((result) => {
console.log(result); // Output: 60
}).catch((error) => {
console.error("Error:", error);
});
Example 2: Usingasync
and await
async function processNumbers() {
let number1 = await new Promise((resolve) => setTimeout(() => resolve(10), 1000));
console.log(number1); // Output: 10
let number2 = number1 * 2;
console.log(number2); // Output: 20
let number3 = number2 * 3;
console.log(number3); // Output: 60
}
processNumbers();
In this chapter, we explored the fundamentals of asynchronous programming in JavaScript, focusing on Promises and the async/await
syntax. These powerful tools enable you to write cleaner, more readable, and efficient asynchronous code.
Asynchronous programming is a crucial part of JavaScript, especially when dealing with tasks like fetching data from a server or reading files. Practice using Promises and async/await
in your projects to get a firm grasp on these concepts.
In the next chapter, we'll dive into the world of JavaScript modules and how they can help you organize your code better.
Happy coding!