Promises and Async/Await in JavaScript ES6
async await in JavaScript ES6 example
Asynchronous programming is essential in modern JavaScript development. Whether you're fetching data from an API or performing background tasks, JavaScript's Promises and Async/Await make asynchronous operations more readable and efficient.
In this guide, we'll explore:
What are Promises?
How Promises work
Common Promise methods
Introduction to Async/Await
How Async/Await simplifies code
Real-world examples
Best practices
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation.
const promise = new Promise((resolve, reject) => {
// asynchronous operation
if (success) {
resolve('Success!');
} else {
reject('Error occurred');
}
});
Pending – Initial state
Fulfilled – Operation completed successfully
Rejected – Operation failed
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Done"));
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Introduced in ES2017, async
and await
make asynchronous code look and behave more like synchronous code.
async function fetchData() {
try {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
Â
Use Promises when chaining multiple async tasks or using concurrent operations (e.g. Promise.all
).
Use Async/Await when readability and top-down execution is preferred.
Always handle errors using .catch()
or try...catch
Avoid mixing await
with .then()
unnecessarily
Use Promise.all()
or Promise.race()
for multiple concurrent requests
const urls = ['url1', 'url2'];
const requests = urls.map(url => fetch(url).then(res => res.json()));
Promise.all(requests)
.then(results => console.log(results))
.catch(err => console.error(err));
Promises and Async/Await are fundamental to handling asynchronous operations in modern JavaScript. They offer powerful ways to manage operations like API requests, timers, and more.
By mastering them, you’ll write more readable, manageable, and bug-free asynchronous code
Â