Asynchronous JavaScript (Callbacks)¶
In the real world, scripts often need to do things that take time (like downloading an image). We don't want the whole website to "freeze" while waiting.
1. Callbacks¶
A callback is a function passed as an argument to another function.
Sequence Control¶
Suppose you want to do a calculation, and then display the result.
function myDisplayer(some) {
console.log(some);
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer); // 10
Real World Example (Waiting)¶
setTimeout(function() { myFunction("I love You !!!"); }, 3000);
function myFunction(value) {
console.log(value);
}
In the example above, myFunction is used as a callback. It is passed to setTimeout(). 3000 is the number of milliseconds before it times out.
2. Callback Hell¶
When you have many nested callbacks, the code becomes hard to read. This is called "Callback Hell".
setTimeout(function() {
getData(function(value) {
parseData(value, function(result) {
display(result);
});
});
}, 1000);
Solution
To solve Callback Hell, JavaScript introduced Promises.