LUH3417 LUH3417 - 1 year ago 63
Javascript Question

Is there any reason why callbacks themselves should be asynchronous

I often read that callbacks in Javascript are asynchronous. This confuses me. What is the main purpose of a callback in asynchronous control flows? To provide the result of an asynchronous computation. Pursuing this idea, such a callback is the replacement of the useless return statement, since this acts synchronously.

Once an asynchronous function is completed it calls its callback with the result. Why should this call be asynchronous as well? What would be the benefit of such behavior?

So the important distinction here is that callbacks themselves are hardly ever asynchronous, but the functions they are passed to, are. Is this distinction misleading?

I am aware that this is a rather academic question, since it doesn't make much difference in the end, if the callback or its caller acts asynchronously. It's just for clarification.

EDIT: I know that there are a lot of use cases for synchronous callbacks along with synchronous functions calling them (, etc.). That's not my point!

Definition of an asynchronous function: It returns immediately but is evaluated later in subsequent iterations of the event loop.

Bonus question: Is there a use case for a really asynchronous callback passed to an synchronous function?

Answer Source

A callback by itself is not "asynchronous" or "synchronous". It's just a function. A neither is the function call asynchronous.

When we say that a function is asynchronous, we mean that it still does things after having returned.

Is this distinction misleading?

No, it proves your point. But the distinction is often unncessary, as everyone knows what is meant. And sometimes we say "asynchronous callback" to mean that a function takes a callback function which will be called asynchronously, i.e. after the function has ended.

Is there a use case for a really asynchronous callback passed to an synchronous function?

It's quite possible to come up with one. Depending on your terminology, promisify(setTimeout) would be a likely candidate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download