Let's have some asynchronous function:
function make() {
setTimeout(function() {
console.log('1');
}, 3000);
}
Let's use this function like this:
make();
console.log('2'); // it will be executed first
Let's say we want to make the second output
to the console execute after an asynchronous
operation within the function is completed.
One approach used for this is to use
callback
:
let's wrap the waiting code in an anonymous
function and pass as a parameter to the
make
function:
make(function() {
console.log('2');
});
Of course, this alone will not solve our
problem. For now, we've just made the
following agreement: if you want to
execute a code after make
fires,
pass that code as a callback to the
make
call.
Let's fix the code of the make
function so that it starts working
in accordance with our agreement:
function make(callback) {
setTimeout(function() {
console.log('1'); // some asynchronous operation, maybe more than one
callback(); // then our callback
}, 3000);
}
Tell me in what order the numbers will be displayed in the console: