In this tutorial, you will learn about JavaScript promise vs async/await.
JavaScript provides Promises and async/await to handle asynchronous operations like API calls, database queries, etc.
What is a Promise?
Promise is used to handle asynchronous operations. It has three states.
- Pending
- Fulfilled
- Rejected
Note: We use Promises, when you need parallel execution,
Example 1:
const data = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
Example 2:
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error));
What is async/await?
async/await is used to handle asynchronous operations. It makes async code look like synchronous code.
Example:
async function fetchData() {
const data = await fetch(url);
return data;
}
Difference between Promises vs async/await
| Promises | async/await |
|---|---|
| In the syntax, it has .then() | In the syntax, It has await |
| It is more complex to read | It is very Cleaner & readable |
| Debugging is very hard. | Debugging is very easy. |
| Prmises has chaining. | There is no need chaining in async/await |
What is the common mistake in async/await
A developer can make a mistake when using async/await.
1. Using await without async.
2. Using forEach with async/await.
3. Forgetting error handling.