Understanding Callback Hell and Promises
Writing asynchronous code in JavaScript can sometimes give you a headache, especially when dealing with Callback Hell. This article discusses the problem and how Promises and Async/Await solve it.
1What is Callback Hell?
Callback Hell (sometimes called the Pyramid of Doom) is a condition where we have many nested callbacks, or callback functions inside other callback functions. This makes JavaScript code very hard to read and maintain.
// Contoh Callback Hell
getData(function(a) {
getMoreData(a, function(b) {
getMoreData(b, function(c) {
getMoreData(c, function(d) {
console.log(d);
});
});
});
});
2The Solution with Promises
Promises were introduced to solve the structural problem of Callback Hell. A Promise represents a value that may not be available yet, but will be resolved or rejected in the future.
// Contoh menggunakan Promises
getData()
.then(function(a) {
return getMoreData(a);
})
.then(function(b) {
return getMoreData(b);
})
.then(function(c) {
return getMoreData(c);
})
.then(function(d) {
console.log(d);
})
.catch(function(error) {
console.error(error);
});
3Async / Await (Modern JS)
With the advent of ES8 (2017), we were introduced to Async/Await, which is actually built on top of Promises. It makes writing asynchronous code look synchronous (running sequentially).
// Contoh menggunakan Async/Await
async function processData() {
try {
const a = await getData();
const b = await getMoreData(a);
const c = await getMoreData(b);
const d = await getMoreData(c);
console.log(d);
} catch (error) {
console.error(error);
}
}