Asynchronous JavaScript Callbacks

Asynchronous callbacks are functions passed to another function that starts executing code in the background. Typically, when the code in the background finishes, the async callback function is called as a way of notifying and passing on data to the callback function that the background task is finished.

History

Asynchronous callbacks was pretty much all JavaScript developers had available to them until 2012 when promises was introduced in many popular libraries, and finally made it to the official ECMAScript standard in 2015. Most modern APIs and libraries tend to use promises instead of callbacks, but async callbacks are still widely used.

Code example: synchronous callback

const arr = [1, 2, 3]
const doubler = x => x * 2
const doubled = arr.map(doubler)

Here we pass the function doubler to the map method. map does not do anything in the background, and the function we pass is therefore also classified as a synchronous callback. But the syntax of asynchronous and synchronous callbacks is identical. Whether the function is used in an asynchronous or synchronous manner depends on the function or method it's passed to.

Code example: asynchronous callback

const addButton = document.querySelector("#add")
addButton.addEventListener("click", () => {
console.log("You clicked #addButton")
})

The addEventListener method attaches an event handler to a DOM element. The details of this method is not important here; all we need to know is that the second parameter is treated as an asynchronous callback function which is only executed when the particular event is triggered on the target node. So, in this case, the async callback function is called every time we click on the #add element.