B
B
be9st2020-03-13 16:16:13
JavaScript
be9st, 2020-03-13 16:16:13

How do callbacks work in js?

Why are the words "async" and "callbacks" related? It's just passing a function to a function. Can you explain CLEARLY how and why asynchrony is achieved through callbacks, preferably with an example (without setTimeout)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Sokolov, 2020-03-13
@be9st

As you already understood and rightly noted, a callback is a function that has been passed somewhere and will be called when necessary.
Asynchrony is not achieved through callbacks. They are just convenient to use where there is asynchrony. Although promises are even more convenient.
Asynchrony occurs where the sequential (line by line) order of code execution breaks. Where one code has already played and released the JS engine - let it cool down, there are no more cases yet. And there were hung event listeners, timers, unresolved promises, long-running ajax requests and other asynchrony.
In these listeners, timeouts and others, they pass in the callback those lines of code that will need to be executed “later”.
Example. Don't want setTimeout then with space button:

function superCallback() {
  console.log("Свершилось! Коллбэк сработал.");
}

document.addEventListener("keydown", superCallback);
// на этот момент мы объявили функцию и повесили слушатель события
// дальше всё, делать больше нечего, движок JS свободен
// но слушатель сидит, ждёт.
The night of asynchrony is coming. No code is working right now. But the listener with the callback is loaded.
Now, if after waiting for a pause, press any key, the listener will work and play the code in the callback aloud.

A
Arseny, 2020-03-13
Matytsyn @ArsenyMatytsyn

In normal built code, the callback is executed either on the fact of the execution condition of the function (not necessarily asynchronous).
In other words, if the function is not executed, then the second one will not be included in the condition. But an error handler, also a function, can become a callback.
I don’t even know, maybe there is a simpler explanation, I tried my best)

R
Rsa97, 2020-03-13
@Rsa97

Callback is exactly the transfer of a function to a function. The passed callback will be called when any conditions are met.
An example of a synchronous callback is the functions map, forEach, reduce, etc., which call a callback for each element of the passed array and wait for a response to be returned to them.
An example of an asynchronous callback is setTimer, setInterval, fetch. In this case, the callback is queued for execution by the JS core when a certain condition is met - the specified time has come or a response has arrived from the server. The main function has already completed its work by that time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question