Callbacks and Asynchronous Are Different!

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

Image for post
Image for post

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 😃

A student who loves to talk about Business and Web Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store