The knowledge points of callback function in JavaScript are all here!

Author: shade
Translator: front end Xiaozhi
Source: dmitripavlutin

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this bowl washing wisdom who is still washing dishes in the early morning.

This article GitHub It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

Callback function is one of the concepts that every JS developer should know. Callbacks are used in arrays, timer functions, promise, event handlers, etc.

In this article, we will explain the concept of callback function. In addition, it will help Zhimi distinguish between two kinds of callbacks: synchronous and asynchronous.

1. Callback function

We write a greeting function. First, we create a function greet(name), which returns a welcome message:

function greet(name) {
  return `Hello, ${name}!`;

greet('Xiao Zhi'); // =>'Hello, Xiao Zhi!'

What if you want to greet some people? Here, we can use array Map() method:

const persons = ['Xiao Zhi', 'Wang Daye']
const messages =

messages // ["Hello, Xiaozhi!", "Hello, Wang Daye!"] accepts each item of the person array and uses each item as a call parameter to call the function greet(): greet('xiaozhi ') and greet('wang Daye').

The interesting thing is people The map (greet) method takes the greet() function as an argument. Doing so makes reet() a callback function. is a function that accepts another function as a parameter, so it is named a higher-order function.

The higher-order function takes full responsibility for calling the callback function and provides it with correct parameters.

In the previous example, the higher-order function people Map (greet) is responsible for calling the greet() callback function and taking each item of the array as parameters: 'Xiaozhi' and 'Wang Daye'.

We can write our own higher-order functions using callbacks. For example, there is an equivalent array Map() method

function map(array, callback) {
  const mappedArray = [];
  for (const item of array) { 
  return mappedArray;

function greet(name) {
  return `Hello, ${name}!`;

const persons = ['Xiao Zhi', 'Wang Daye']

const messages = map(persons, greet);

messages // ["Hello, Xiaozhi!", "Hello, Wang Daye!"]

map(array, callback) is a high-order function because it takes a callback function as a parameter and then calls the callback function: callback(item) inside its function body.

2. Synchronous callback

Callback can be called in two ways: synchronous callback and asynchronous callback.

Synchronous callbacks are executed during the execution of higher-order functions that use callbacks.

In other words, synchronous callbacks are blocked: higher-order functions cannot complete their execution until the callback completes its execution.

function map(array, callback) {
  console.log('map() start');
  const mappedArray = [];
  for (const item of array) { mappedArray.push(callback(item)) }
  console.log('map() complete');
  return mappedArray;

function greet(name) {
  console.log('greet() Called ');
  return `Hello, ${name}!`;
const persons = ['Xiao Zhi'];

map(persons, greet);

// map() start
// greet() is called 
// map() complete

greet() is a synchronous callback function because it executes simultaneously with the higher-order function map().

2.1 example of synchronous callback

Many native JavaScript type methods use synchronous callbacks.

The most common is array methods, such as array map(callback),array.forEach(callback),array.find(callback),array.filter(callback),array.reduce(callback, init):

// Example of a synchronous callback on an array

const persons = ['Xiao Zhi', 'Front end Xiaozhi']
  function callback(name) {
// Xiao Zhi
// Front end Xiaozhi

const nameStartingA = persons.find(
  function callback(name) {
    return name[0].toLowerCase() === 'Small';
// nameStartingA / / Xiaozhi

const countStartingA = persons.reduce(
  function callback(count, name) {
    const startsA = name[0].toLowerCase() === 'Small';
    return startsA ? count + 1 : count;

countStartingA // 1

3. Asynchronous callback

Asynchronous callbacks are executed after higher-order functions are executed.

In short, asynchronous callbacks are non blocking: higher-order functions do not have to wait for the callback to complete its execution, and higher-order functions ensure that the callback is executed later on a specific event.

In the following example, the execution delay of the later() function is 2 seconds

console.log('setTimeout() start')
setTimeout(function later() {
  console.log('later() Called')
}, 2000)
console.log('setTimeout() complete')

// setTimeout() start
// setTimeout() complete
// later() is called (after 2 seconds)

3.1 example of asynchronous callback

Asynchronous callback of timer function:

setTimeout(function later() {
  console.log('2 Seconds have passed!');
}, 2000);

setInterval(function repeat() {
  console.log('Every 2 seconds');
}, 2000);

DOM event listeners also call event handlers (a subtype of callback functions) asynchronously

const myButton = document.getElementById('myButton');

myButton.addEventListener('click', function handler() {
  console.log('I was clicked!');
// When you click the button, you will print 'I was clicked!'

4. Asynchronous callback function vs asynchronous function

The special keyword async placed before the function definition creates an asynchronous function:

async function fetchUserNames() {
  const resp = await fetch('');
  const users = await resp.json();
  const names ={ login }) => login);

fetchUserNames() is asynchronous because its prefix is async. This function await fetch(' ') from the first 5 users of GitHub. Then extract the JSON data from the response object: await resp json().

The async function is the syntax sugar of promise. When the expression await < promise > is encountered (note that calling fetch() will return a promise), the asynchronous function will pause until the promise is resolved.

Asynchronous callback functions and asynchronous functions are different terms.

Asynchronous callback functions are executed by higher-order functions in a non blocking manner. However, the asynchronous function pauses its execution while waiting for promise (await < promise >) to resolve.

However, we can use asynchronous functions as asynchronous callbacks!

Our asynchronous function fetchUserNames() is set as the asynchronous callback called when the button is clicked:

const button = document.getElementById('fetchUsersButton');

button.addEventListener('click', fetchUserNames);


A callback is a function that can be accepted as a parameter and executed by another function (higher-order function)

There are two kinds of callback functions: synchronous and asynchronous.

The synchronous callback function is executed simultaneously with the higher-order function using the callback function, and the synchronous callback is blocked. On the other hand, the execution time of asynchronous callbacks is later than that of higher-order functions, and asynchronous callbacks are non blocking.

End ~, thank you for watching. I'm Xiaozhi. I'll wash the dishes!

The bugs that may exist after code deployment cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful BUG monitoring tool Fundebug.

Original text:


There are dreams and dry goods. Wechat search [Daqian world] pays attention to this bowl washing wisdom who is still washing dishes in the early morning.

This article GitHub It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

Keywords: Javascript Front-end Vue.js

Added by wjwolf79 on Thu, 13 Jan 2022 02:24:52 +0200