What is asynchronous? What is synchronization?
If you can get the results directly, that is synchronization, such as registration in the hospital, get the number to leave the window. The synchronization task may take 10 milliseconds or 3 seconds.
If you can’t get the results directly, that is asynchronous, such as waiting at the door of the restaurant, get the number can go shopping first, then when can you really eat? You can go to the restaurant to ask every 10 minutes (polling), or you can scan the code and receive notifications via wechat (callback).
Asynchronous, for example,
var request = new XMLHttpRequest()
request.open('GET'.'/a/b/c? name=ff'.true);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
console.log(request.responseText); }}; request.send();Copy the code
AJAX, for example, the request. The send (), and not directly by the response, must wait until after the readyState into 4, the browser back to invoke the request. The onreadystatechange function, We can get request. Response, which is similar to the process of a restaurant sending a wechat reminder.
What is a callback
- Write to your own function, not a callback
- The functions that I write for other people are called callbacks
A callback is a function that is written but not called by someone else. Request. The onreadystatechange is intended for the browser calls, which means that the browser back to call the function.
The callback example
function f1() {}
function f2(fn) {
fn()
}
f2(f1)
Copy the code
F (f1) is not called by itself but is passed to F (f2), f (F1) is called by f (f1), f (f1) is written to a function called by F (F2).
The relationship between asynchrony and callback
The association between asynchrony and callback:
The asynchronous task needs to notify JS to get the result when it gets it. How do you notify JS to get the result?
You can ask JS to leave a function address (phone number) to the browser. When the asynchronous task is complete, the browser can call the function address (call the phone number), and pass the result as an argument to the function (call the phone number). This function is written for the browser to call, so it is a callback function.
The difference between asynchrony and callback:
- Asynchronous tasks require a callback function to notify the results (not necessarily a callback, you can also use polling)
- But callbacks don’t have to be used only for asynchronous tasks. They can be used for synchronous tasks, such as
array.forEach(n => console.log(n))
Is a synchronous callback
Determine synchronous versus asynchronous (by feature or document)
A function is asynchronous if its return value is inside (and not limited to) setTimeout, AJAX (i.e. XMLHttpRequest), and AddEventListener.
Request.open (Method, URL, false) can set AJAX to synchronous, but generally do not set AJAX to synchronous, doing so will cause the page to get stuck during the request.
Example of an asynchronous function – roll the dice
functionRoll the dice,) {
setTimeout(() = > { // Arrow function
return parseInt(Math.random() * 6) + 1
}, 1000)
//return undefined
}
constN = roll the dice ()console.log(n) //undefined
Copy the code
Roll the dice () does not say return, it is return undefined, the arrow function has return, it returns the real result, so this is an asynchronous function/asynchronous task.
So how do you get asynchronous results?
You can use callbacks. Write a function and give him the address of the function.
function f1(x) {console.log(x)} Roll the dice (f1)Copy the code
And then I’m going to take the die roll function and I’m going to pass that as a parameter to F1.
functionRoll the dice,fn) {
setTimeout(() = > {
fn(parseInt(Math.random() * 6) + 1)},1000)}Copy the code
Since F1 is declared only once, you can delete f1 and simplify to an arrow function.
function f1(x) {console.log(x)} Roll the dice (f1)/ / toRoll the dice,x= > console.log(x))
// Let's simplify this toRoll the dice,console.log) // If the number of parameters is inconsistent, this cannot be simplified
Copy the code
Roll the dice example complete code:
functionRoll the dice,fn) {
setTimeout(() = > {
fn(parseInt(Math.random() * 6) + 1)},1000} roll the dice (x= > console.log(x)) // Print a random number from 1 to 6
Copy the code
conclusion
- The asynchronous task cannot get the result
- So we pass a callback to the asynchronous task
- The callback is invoked when the asynchronous task is complete
- The call takes the result as an argument
Ps interview question: What is the printout of the following code?
const array = ['1'.'2'.'3'].map(parseInt)
console.log(array)
Copy the code
Answer: [1, NaN, NaN] (error simplification of arrow functions)
The above code, before simplification, looks like this:
const array = ['1'.'2'.'3'].map((item, i, arr) = > {
return parseInt(item, i, arr) //parseInt takes only two arguments, so arr is ignored
}
ParseInt ('1', 0, arr) => 1 (0 is an invalid parameter, so the result is 1)
ParseInt ('2', 1, arr) => NaN ('2', 1, arr) => NaN ('2', 1, arr) => NaN ('2', 1, arr)
//parseInt('3', 2, arr) => NaN (parseInt('3', 2, arr) => NaN (parseInt('3', 2, arr))
console.log(array) //[1, NaN, NaN]
Copy the code
To write correctly:
const array = ['1'.'2'.'3'].map(item= > parseInt(item))
console.log(array) / / [1, 2, 3]
Copy the code