How to know if a Javascript Callback is Synchronous or Asynchronous?

You have several questions here, so I'll try to answer them one by one:

Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?

In the browser you can kinda have this as the rule of thumb: Only setTimeout, setInterval, requests and events are asynchronous. Other built-in callbacks (like Array.prototype.map) are synchronous.

On Node.js it's more complicated: e.g. you can do file reading both synchronously and asynchronously. Then you just need to know that the callback is asynchronous by nature.

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

Unfotunately without checking the source code of the method/function you're calling you cannot know if it's synchronous or asynchronous.

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up.

Exactly. You can find this from jQuery's documentation for .hide method:

complete
Type: Function()
A function to call once the animation is complete, called once per matched element.


A callback is a function that will get executed once an Asynchronous process is completed. Let's say we have an object person with the following data.

var person = {
 id: 1034
 name: 'Julio',
 age: 23,
 moneyInBank: 0
}

We want to get the the moneyInBank for this person but we don't have access to that information in our local environment. We need to get it from a database in another server, this could take a while depending internet connection, optimization, etc.

getMoneyInBank(person.id, callback) is going to go over that process and fetch the information we need. If we were to run the next script without the callback.

getMoneyInBank(person.id);
console.log(person.money);

We will get 0 in the output because getMoneyInBank has not finished by the time the log is executed. If we want to make sure we will print meaningful information we need to change our code to something like this.

getMoneyInBank(persion.id, function(){
  console.log(person.money);
});

Using a callback the log only is going to be called when getMoneyInBank finishes.

Tags:

Javascript