Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Mastering Asynchronous JavaScript- Callbacks, Promises, and Async:Await

Uploaded by

Shopre
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Mastering Asynchronous JavaScript- Callbacks, Promises, and Async:Await

Uploaded by

Shopre
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Introduction

Asynchronous programming is crucial for modern web


applications. JavaScript, with its non-blocking nature,
relies heavily on asynchronous operations. In this post,
we’ll explore the evolution of handling asynchronous
operations in JavaScript, from callbacks to Promises and
async/await, to help you write cleaner and more
manageable code.

Callbacks: The Foundation of Asynchronous


JavaScript

Callbacks are the simplest form of handling asynchronous


operations. A callback is a function passed as an argument
to another function and is executed after some operation
has been completed.

Example: Callback Hell

setTimeout(() => {
console.log('First');
setTimeout(() => {
console.log('Second');
setTimeout(() => {
console.log('Third');
}, 1000);
}, 1000);
}, 1000);
While callbacks are straightforward, they can quickly
become unmanageable, leading to what is known as
“callback hell.”

Promises: A Better Way to Handle


Asynchronous Operations

Promises provide a more elegant way to handle


asynchronous operations, allowing for better readability
and error handling. A Promise represents an operation that
hasn’t completed yet but is expected to in the future.

Example: Basic Promise

const fetchData = () => {


return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched');
}, 1000);
});
}
fetchData().then(data => console.log(data)).catch(error => console.error(error));

Promises can be chained, making it easier to handle


sequences of asynchronous operations.

Example: Chaining Promises

fetchData()
.then(data => {
console.log(data);
return 'Processing data';
})
.then(result => console.log(result))
.catch(error => console.error(error));

Async/Await: Syntactic Sugar for Promises

Async/await, introduced in ES2017, provides an even


cleaner way to work with Promises. It allows you to write
asynchronous code as if it were synchronous, making it
easier to read and maintain.

Example: Async/Await

const fetchDataAsync = async () => {


try {
const data = await fetchData();
console.log(data);
const result = await 'Processing data';
console.log(result);
} catch (error) {
console.error(error);
}
}
fetchDataAsync();

Real-World Example: Fetching Data from an


API

Let’s put it all together with a real-world example of


fetching data from an API.

Example: Fetching Data with Async/Await


const fetchUserData = async (userId) => {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/$
{userId}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetching user data failed:', error);
}
}
fetchUserData(1);

In this example, we use the fetch API to get user data,


handling errors gracefully with try/catch blocks.

Conclusion

Understanding asynchronous programming in JavaScript is


essential for modern web development. Callbacks,
Promises, and async/await each provide unique ways to
handle asynchronous operations. By mastering these
techniques, you can write more efficient, readable, and
maintainable code. Happy coding!

You might also like