Asynchronous Operations with Promises and Async/Await
Proper handling of asynchronous operations is essential for modern JavaScript development, especially when handling
I/O operations such as network requests or accessing files Promise and
async/await
provide powerful tools for checking this asynchronous code on.
Promises
A promise is an object that represents the eventual completion or failure of an asynchronous operation.
Creating a Promise
Let's create a simple promise in JavaScript,
Syntax-
let promise = new Promise((resolve, reject) => {
// Asynchronous operation
if (success) {
resolve(value); // On success
} else {
reject(error); // On failure
}
});
Example-
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Operation successful");
}, 1000);
});
promise.then((result) => {
console.log(result); // "If Operation successful"
}).catch((error) => {
console.error(error); // "If Operation failed"
});
Chaining Promises
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000);
});
promise
.then(result => {
console.log(result); // 1
return result * 2;
})
.then(result => {
console.log(result); // 2
return result * 2;
})
.then(result => {
console.log(result); // 4
})
.catch(error => {
console.error(error);
});
async/wait
async/await
is a syntax sugar built on top of Promises, providing a straightforward way to execute asynchronous code.
Using async
Functions
async function functionName() {
// Asynchronous code
let result = await promise;
// Process result
}
Example-
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchData();
Error Handling in async/await
async function riskyOperation() {
try {
let result = await someAsyncFunction();
console.log(result);
} catch (error) {
console.error("Error during risky operation:", error);
}
}
riskyOperation();
Combining promise and async/wait
You can mix Promises and have async/await
flexibility and handle asynchronous operations.
Example-
async function fetchData(url) {
let response = await fetch(url);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
}
function logData(url) {
fetchData(url)
.then(data => console.log(data))
.catch(error => console.error("Error fetching data:", error));
}
logData("https://api.example.com/data");
Best Practices
Always handle errors- use catch
for promises and
try…catch
for async/await
to handle errors.
Use async/await
for readability- When handling a lot of asynchronous operations,
async/await
tends to result in cleaner and more readable code.
Avoid Mixing- want to use Promises or async/await
in a given piece of code for clarity.
Graceful Degradation-
Make sure your code can handle failures gracefully, providing fallback options or user notifications.
With proper use of Promises and async/await
, you can manage asynchronous functions more effectively in JavaScript, resulting in more maintainable and reliable code.
Also, Read: Error Handling in JavaScript
Leave Comment