Callbacks
Callbacks are the first thing we should understand when we are talking about concurrency. The good news is that the callback
principle is not too hard to understand. It is just a function that takes another function as an argument, which is then called when the rest of the initial function has finished. In other words, it's just a function calling a function, like this:
function doSomething(callback) {
callback();
}
function sayHi() {
console.log("Hi!");
}
doSomething(sayHi);
The doSomething()
function, which is created with the parameter callback
, is just calling whatever function is being passed in as an argument. We call it using the sayHi()
function as an argument, so this code snippet is just a very complicated way to get Hi!
printed to the console.
Here is an example of the callback
principle actually doing something:
function judge(grade) {
switch (true) {
case grade == "A":
console.log("...