Abstract: This article will explain the concept of callbacks and help you distinguish between two types of callbacks: synchronous and asynchronous.
The original link: segmentfault.com/a/119000003…
The callback function is one of those concepts that every front-end programmer should know. Callbacks can be used in arrays, timer functions, promises, event handling.
This article will explain the concept of callbacks and help you distinguish between two types of callbacks: synchronous and asynchronous.
The callback function
Let’s start by writing a function that greets people.
Create a greet(name) function that takes the name argument. This function should return a greeting message:
What if you greet a lot of people? This can be done with the special array method array.map() :
Persons.map (greet) gets all elements of persons and calls the greet() function with each element as a parameter: ‘greet(‘Cristina’), greet(‘Ana’).
Persons.map (greet) accepts the greet() function. So greet() becomes the callback function.
Persons.map (greet) is a function that takes another function as an argument, so it is called a higher-order function.
Callbacks are arguments to higher-order functions that perform operations by calling them.
The important thing is that the higher-order function is responsible for calling the callback and providing it with the correct arguments.
In the preceding example, persons.map(greet) calls the greet() function with ‘Cristina’ and ‘Ana’ as parameters.
This provides a simple rule for identifying callbacks. If you define a function and pass it as an argument to another function, then this creates a callback.
You can write your own higher-order functions that use callbacks. Here is the equivalent version of the array.map() method:
Map (array, callback) is a higher-order function because it takes a callback function as an argument and then calls that callback function inside its body: callback(item).
Note that regular functions (defined with the keyword function) or arrow functions (defined with the bold arrow =>) can also be used as callbacks.
Synchronous callback
Callbacks can be invoked in two ways: synchronous and asynchronous.
Synchronous callbacks are “blocking” : higher-order functions do not continue execution until the callback is complete.
For example, call the map() and greet() functions.
Greet () is a synchronous callback.
Steps to synchronize the callback:
- Higher-order functions start executing:
'map() starts'
- The callback function executes:
'greet() called'
- Finally, the higher-order function completes its own execution:
'map() completed'
Example of synchronous callback
Many native JavaScript types of methods use synchronous callbacks.
The most commonly used are array methods, such as:array.map(callback)
.array.forEach(callback)
.array.find(callback)
.array.filter(callback)
.array.reduce(callback, init)
The string.replace(callback) method can also accept callbacks executed synchronously:
An asynchronous callback
Asynchronous callbacks are “non-blocking” : higher-order functions complete their execution without waiting for the callback to complete. Higher-order functions ensure that callbacks are executed later on a particular event.
In the following example, the later() function is delayed by 2 seconds:
Later () is an asynchronous callback because setTimeout(later ‘, ‘2000) starts and completes execution, but later() is executed 2 seconds later.
Steps to invoke a callback asynchronously:
- Higher-order functions start executing:
'setTimeout()starts'
- Higher-order functions complete their execution:
'setTimeout() completed'
- The callback is executed after 2 seconds:
'later() called'
Examples of asynchronous callbacks
Timer function asynchronously calls callback:
DOM event listeners also invoke event handlers (subtypes of callback functions) asynchronously:
Asynchronous callback and asynchronous functions
Prefixes the function definition with the special keyword async to create an asynchronous function:
FetchUserNames () is asynchronous because it is prefixed with async. Functions await the fetch (‘ https://api.github.com/users?per_page=5 ‘) out before get 5 users. Then extract the JSON data from the response object: await resp.json().
Asynchronous functions are syntactic sugar on top of promises. When encountering the expression await
Asynchronous callback function and asynchronous function are two different terms.
Asynchronous callback functions are executed by higher-order functions in a non-blocking manner. But asynchronous functions pause while waiting for the promise (await
But you can use asynchronous functions as asynchronous callbacks!
Let’s make the asynchronous function fetch UserNames() an asynchronous callback that can be called with a click of the button:
conclusion
A callback is a function that can be passed as an argument to another function (a higher-order function).
There are two types of callback functions: synchronous and asynchronous.
The synchronization callback is blocked.
Asynchronous callbacks are non-blocking.
SetTimeout (callback ‘ ‘, ‘ ‘0)