Callbacks and Asynchronous Are Different!

Oussema Miled
2 min readSep 25, 2020

We’re gonna talk about why we can’t assume that a function is asynchronous even if it takes a callback.

Perquisites

A fair understanding of JavaScript and asynchronous programming.

What makes a function asynchronous?

Maybe you’re answer is “when argument of a function is a function”. Basically yes, but not exactly, every asynchronous function takes a function argument, but not every function that does so is asynchronous because argument function can be called synchronously.

How?

Simply taking a callback doesn’t make a function asynchronous. There are many examples of functions that take a function argument but are not asynchronous. For example there’s forEach in Array. It iterates over each item and calls the function once per item.

For this example, the code is executed step by step even though we have a callback, actually it won’t work as we want otherwise. Other examples of this would be the sort method which takes also a callback but still synchronous. In the other hand setTimeout takes a callback and it’s asynchronous. So functions with callbacks can be synchronous or asynchronous.

To conclude

For a function to be asynchronous, it needs to perform an asynchronous task, it should incorporate the argument callback in handling the results of this asynchronous operation. For instance, let’s say we need to get data from a server asynchronously then run operations on that data. Something like the following:

That’s all, hopefully now you have a clear understanding of the difference. See you in the next articles 😃

PS: If you like what I do and want to support me, you can do that by becoming a medium member using this link

--

--

Oussema Miled

A Computer Science Engineer who loves to talk about Web Development and sometimes other stuff!