From Promises to Async/Await
With the introduction of Promise in ES6, asynchronous handling became more convenient, but there was still a readability issue when the then-chaining became long or the tasks grew more complex.
To address this issue, async/await was introduced in ES7.
Async/await replaces the traditional then-chaining and simplifies asynchronous code. By using try-catch blocks, asynchronous code can be written as if it were synchronous, which greatly improves readability and reduces complexity.
// Original Promise-based chaining
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) resolve('Data fetched!');
else reject('Error occurred!');
}, 1000);
});
};
fetchData()
.then((data) => {
console.log(data);
return 'Proceeding to the next step';
})
.then((nextStep) => {
console.log(nextStep);
})
.catch((error) => {
console.error(error);
});
// Converted to async/await
const fetchDataAsync = async () => {
try {
const data = await fetchData();
console.log(data); // 'Data fetched!'
const nextStep = 'Proceeding to the next step';
console.log(nextStep);
} catch (error) {
console.error(error); // Handle error
}
};
fetchDataAsync();