What are synchronous and asynchronous?

  • Synchronization: Direct access to the results

  • Asynchronous: Can’t get the result directly

In JS, some functions do not get results immediately, but need to wait a while to get results, such as sending an HTTP request and waiting for a response.

If JS cannot get the result of a function directly, it can first execute other code and wait for the result to get the result again, this is asynchronous

The benefit of asynchrony is that time spent waiting can be spent doing something else

How do you tell if a function’s results are synchronous or asynchronous?

A function is asynchronous if its return value is inside setTimeout, AJAX, or AddEventListener

What is a callback?

We want to get the results of the asynchronous function in two ways: polling and callback

  • Polling is when I check regularly to see if I got the results
  • The callback is I write a function, fn, and I pass it to the asynchronous function, and when the asynchronous function finishes executing, fn is called, so we get the result of the asynchronous processing through the callback

A function that satisfies the following conditions is a callback function: a function that I write for others to use but do not use myself

For example:

  1. ForEach ((item)=>console.log(item)) (item)=>console.log(item) the arrow function is A callback

  2. Sometimes can also pass a callback object, when we write an AJAX request, we pass the callback to the request. The onreadystatechange, waiting for the browser to invoke

The functions shown in yellow are the callback functions

Note: Callbacks can be used for synchronous tasks, not necessarily asynchronous tasks

The callback example

functionRoll the dice,){
	setTimeout(() = >{
  	return parseInt(Math.random()*6) + 1
  },1000)}Copy the code

Notice that in this code,

Roll the dice () without return ()

The arrow function has a return in it that returns the actual result, so it’s an asynchronous function

constN = roll the dice ()console.log(n)/ / n is Undefined
Copy the code

So how do we get the result of setTimeout?

You can use callbacks

function callback(x) {
	console.log(x)} Roll the dice (callback){setTimeout(() = >{
  	callback(parseInt(Math.random()*6) + 1)},1000)}Copy the code

We can reduce the callback function to an arrow function

Roll the dice,x= >{
console.log(x)
})

// Since the parameters of the function are the same as the values to be used, it can be reduced toRoll the dice,console.log)
Copy the code

But if you don’t have the same number of arguments, you can’t simplify this,

For example:

const array = ['1'.'2'.'3'].map(parseInt) the result is [1.NaN.NaN]
Copy the code

The reason for the error is that the Map and parseInt functions have different arguments

First, let’s review the map function

let new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])
Copy the code

The map callback takes three parameters: currentValue, index, and array itself

ParseInt has two arguments, String and Radix, which means to convert a string string to an integer based on radix

parseInt(String, Radix) convert a string string to integer radixCopy the code
const array = ['1'.'2'.'3'].map(parseIntThis is equivalent to ['1'.'2'.'3'].map((currentValue, index, array) = > {
	parseInt(currentValue, index, array)
  // parseInt('1', 0)
  ParseInt ('2', 1); // parseInt('2', 1)
  ParseInt ('3', '2'); // parseInt('3', '2')
})
Copy the code

The following is the correct way to write, is to specify the parameters

['1'.'2'.'3'].map((currentValue, index, array) = > {
	parseInt(currentValue)
}
Copy the code

Third, summary

Let’s summarize the relationship between asynchrony and callbacks

  • The asynchronous task cannot get the result

  • So we pass a callback to the asynchronous task

  • The callback function is called when the asynchronous task is complete

  • The call takes the result as an argument