🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to JavaScript Notes
Topic #222

Async Callbacks

"I will call back later!"

A callback is a function passed as an argument to another function.

The receiving function decides when to use (call) the callback.

A callback can be called immediately, later, once, or many times.

By themselves, callbacks are neither synchronous nor asynchronous.

They are simply a way to let one function execute another function.

Why Use Callbacks?

Callbacks make functions more flexible.

Instead of hardcoding what should happen next, a function can let the caller decide by supplying a callback.

Example

// A Greet Function

function greet(name, callback) {

  callback("Hello " + name);

}

// A Display Function

function display(message) {

  document.getElementById("demo").innerHTML = message;

}

// Call greet() with a callback function (display)

greet("John", display);

The display function is the callback.

The greet() function decides when to call it.


Synchronous Callbacks

Most callbacks execute immediately.

These are called synchronous callbacks because they run before the current function returns.

Example

// Calculate Function

function calculate(x, y, operation) {

  return operation(x, y);

}

// Add Function

function add(a, b) {

  return a + b;

}

// Call calculate() with add as callback

let result = calculate(5, 3, add);

Note: The callback runs immediately while calculate() is executing. No asynchronous behavior is involved.


Built-in Synchronous Callbacks

Many JavaScript methods use synchronous callbacks.

Col 1 Col 2 Col 3
Method Callback Called Asynchronous?
forEach() Once for each element No
map() Once for each element No
filter() Once for each element No
reduce() For each element No
sort() To compare values No

Timing Problems

You cannot see a result before it is computed.

Example

let result;

setTimeout(function() {

  result = 5;

}, 1000);

// What is result here?

The result is undefined because the async code has not finished yet.


The Callback Idea

The solution to the problem above, is to give JavaScript a callback function to call after the result is ready.

A callback is a function passed as an argument to another function.

This technique allows a function to call another function.

Example

function done(value) {

  myDisplayer(value);

}

setTimeout(function() {

  done(5);

}, 1000);

// What is result here?

The value is used inside the callback.

This works because the callback runs later.


Asynchronous Callbacks

Callbacks are also commonly used with asynchronous APIs.

In these cases, the callback runs after the asynchronous operation has completed.

The callback is not what makes the operation asynchronous.

The asynchronous API decides when to call the callback.

Example

// Set a Timeout

setTimeout(function () {myDisplayer("Finished!")}, 3000);

In the example above:

myDisplayer is a callback function passed as an argument to setTimeout().

3000 is the number of milliseconds before myDisplayer will be called.

The browser waits three seconds before calling the callback.

The delay is created by setTimeout(), not by the callback itself.

Note: When you pass a function as an argument, remember not to use parenthesis. Right: setTimeout(myFunction, 3000) Wrong: setTimeout(myFunction(), 3000)


Event Handling

Callbacks are often used in JavaScript, especially in event handling:

User interactions, such as button clicks or key presses, can be handled by providing a callback function to an event listener.

Example

document.getElementById("myButton").addEventListener("click", displayDate);

In the example above, displayDate is a callback function passed as an argument to the addEventListener() method.

displayDate will be called when a user clicks the button with id="myButton".


Sequence Control

Sometimes you would like to have better control over when to execute a function.

Suppose you want to do a calculation, and then display the result.

You could first call the calculator function myCalculator, and then call the display function myDisplayer:

Example

// Funtion to display something

function myDisplayer(some) {

  document.getElementById("demo").innerHTML = some;
}

// Function to calculate a sum

function myCalculator(num1, num2) {

  let sum = num1 + num2;

  return sum;

}

// Call the calculator

let result = myCalculator(5, 5);

// Call the displayer

myDisplayer(result);

Or, you could call the calculator function myCalculator, and let the calculator function call the display function myDisplayer:

Example

// Funtion to display something

function myDisplayer(some) {
  document.getElementById("demo").innerHTML
  = some;
}

// Function to calculate a sum

function myCalculator(num1, num2) {

  let sum = num1 + num2;

  myDisplayer(sum);
}

// Call the calculator

myCalculator(5, 5);

The problem with the first example above, is that you have to call two functions to display the result.

The problem with the second example, is that you cannot prevent the calculator function from displaying the result.

Now it is time to bring in a callback.


Using a callback, you could call the calculator function (myCalculator) with a callback (myCallback), and let the calculator function run the callback after the calculation is finished:

Example (Callbacks)

  function myDisplayer(some) {
  document.getElementById("demo").innerHTML
  = some;
}

function myCalculator(num1, num2, myCallback) {

  let sum = num1 + num2;

  myCallback(sum);
}

myCalculator(5, 5, myDisplayer);

In the example above, myDisplayer is used as a callback function.

It is passed to myCalculator() as an argument.


Callback Chains

Sometimes one callback starts another operation that uses another callback.

This can lead to deeply nested, complex and hard-to-read code.

When callbacks get deep, debugging is difficult. The logic moves from left to right and becomes difficult to follow.

This is often referred to as "callback hell" or the "pyramid of doom".

Example

step1(function(result1) {

  step2(result1, function(result2) {

    step3(result2, function(result3) {

      display(result3);

    });

  });

});

Note: Promises and async/await were introduced to make asynchronous code easier to read and maintain.


Summary

  • A callback is a function passed to another function.
  • Callbacks can be synchronous or asynchronous.
  • The callback itself does not make code asynchronous.
  • Many JavaScript methods use synchronous callbacks.
  • Asynchronous APIs often use callbacks to handle results.
  • Promises and async/await build on the same idea while making asynchronous code easier to write.

Callback is Not Asynchronous

  • A callback is just a function.
  • It may be called immediately (like map() or sort()).
  • It may be called later by an asynchronous API (like setTimeout() or fetch()).
  • The API (not the callback) is what introduces the asynchronous behavior.

Callback Alternatives

Asynchronous callback solutions are difficult to write and difficult to debug.

Because of this, modern asynchronous JavaScript do not use callbacks.

Modern JavaScript offers superior alternatives for handling asynchronous operations, using Promises and the async/await syntax, which provide a cleaner flow and better error handling.


When to Use a Callback?

Callbacks are still important to understand.

Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like waiting for a file to load).

Want to go beyond the notes?

Join CodingNow 2.0's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Async Callbacks – FAQs

Quick answers about learning Async Callbacks in JavaScript.

This free note from CodingNow 2.0 explains Async Callbacks in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on CodingNow 2.0, including Async Callbacks, is 100% free with no signup required.
With focused practice, most students grasp Async Callbacks in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now