- Synchronization function
- asynchronous
- An asynchronous function
- Asynchronous programming
- Give me a chestnut
- The callback function
- Reference article:
Synchronization function
- Typically, browsers execute JS code line by line in code order. In other words,
If the previous line of code is not executed, it will not continue to execute. Instead, it will wait until the execution result of this line of code is returned
.
// It can be used either as a parameter or as a return value
// The todo synchronization function is executed line by line and is called when the code is finished
function add(x,y){
return x+y
}
add(10.20) Copy the code
asynchronous
-
Javascript language execution environment of ‘single thread’.
-
Single-threaded means that you can only complete one task at a time. If there are multiple tasks, they must be queued, the first task completed, the next task executed, and so on.
-
(I actually think computers are microscopically single-threaded, because a machine can only do one thing at a time. However, from a macro point of view, within the scope of our perception of time, it is believed that machines can do more than one thing at a time. This is our perception of asynchrony/multithreading/concurrency. Machines are essentially sequential, which is why there are such things as calculus to study the nature of things.)
-
Synchronization task: A task that is queued to be executed on the main thread can be executed only after the previous task is completed.
-
Asynchronous task: a task that does not enter the main thread but enters the task queue. Only when the task queue notifies the main thread that an asynchronous task is ready to execute will it enter the main thread for execution.
-
Event Loop: Only after all synchronous tasks in the execution stack are executed, the system will read the task queue to see which asynchronous tasks can be executed. Then the corresponding asynchronous tasks end the waiting state and enter the execution stack to start execution.
An asynchronous function
// In general, the purpose of taking a function as an argument is to get the result of an asynchronous operation inside the function
If you need to get the result of an asynchronous operation inside a function, you must use the callback function to get it// Pass a function in at the call location, and call the passed function inside the wrapped function
// js single thread, event loop
console(1) setTimeout((a)= >{// It won't be over until it reaches 3 console.log(2) },100) console.log(3) // Output result: 1 3 2// This is true even if the timer is 0 Copy the code
Asynchronous programming
How to skillfully encapsulate a method with a callback function as if it were a variable
setTimeout
readFile
writeFile
ajax
// This case must go through the: callback function
function add(x,y,callback){// lower level call / equivalent to: //var x =10 , //var y = 20, //var callback= function(result) {console.log(result)} setTimeout((a)= >{// It won't be over until it reaches 3 var result = x+y callback(result)/ / must be callback },100) } // Upper definition add(10.20.function(result){ console.log(result) }) Copy the code
Async await to write async in a synchronous manner
Synchronous:var result = awaitXXX (the promise)Asynchronous: There are callback functionsaxios.get('/xxx'.function() = >{})
Copy the code
Give me a chestnut
Start by creating a Person object for understanding
const person={
eat:(a)= >{console.log('to eat... ')},
sleep:(a)= >{console.log('go to bed... ')},
getUp:(a)= >{console.log('Get up... ')}
}
Copy the code
Then call the internally defined methods respectively:
person.eat() / / to eat...
person.sleep() / / to sleep...
person.getUp() // Get up...
Copy the code
-
In this case, each time the person object calls an internal method, it waits for the execution of the previous method to finish, just as a person can’t eat and sleep, he must wait for the meal to finish before going to sleep. The way this code is executed is called synchronization.
-
Obviously, asynchrony is the opposite of synchronization, where you call code and don’t wait for the result of the call, but return it immediately, and then somehow get the result of the call in the future.
const person = {
eat: (a)= > { console.log('to eat... ')}, sleep: (a)= > { console.log('go to bed... ')}, getUp: (a)= > { console.log('Get up! ')}, setAlarmClock: function setAlarmClock(time) {
setTimeout((a)= > { this.getUp() }, time) console.log('I set an alarm clock.${time}Wake me up after Ms. `) } } person.setAlarmClock(1000) // I set an alarm clock to wake me up after 1000ms. person.eat() / / to eat... person.sleep() / / to sleep... // Wake up now! Copy the code
-
Here the Person object first performs the setAlarmClock function, that is, sets an alarm, and instead of sitting in front of the alarm and waiting for it to go off, it goes to sleep, eats, and then wakes up after the alarm goes off for a second.
-
This mode of execution is called asynchronous.
-
In a word, is synchronous and other results, asynchronous and unequal results.
The callback function
-
What is a callback?
-
As mentioned above, asynchronous code does not wait for the result of the call after it is called, but instead retrieves the result by some means in the future, one of which is a callback.
-
The callback function follows two principles:
- Methods written are not called by themselves, but by others.
- Methods will be executed by someone else at some point in the future, rather than being manually invoked by the developer himself.
// any method that is not called directly by itself is executed in the future. For example, fn() means that I am now executing fn() immediately Copy the code
- Summary: I’ll call later, not now.
Callbacks typically occur in asynchronous programming to get the result of asynchronous processing. The callback function can be passed as an argument to other functions to be called at the appropriate time.
// In general, the purpose of taking a function as an argument is to get the result of an asynchronous operation inside the function
If you need to get the result of an asynchronous operation inside a function, you must use the callback function to get it// Pass a function in at the call location, and call the passed function inside the wrapped function
Copy the code
- If you need to get your current sleep state after your alarm goes off to decide whether to go back to sleep:
const person = {
eat: (a)= > { console.log('to eat... ')}, sleep: (a)= > { console.log('go to bed... ')}, getUp: (a)= > { console.log('Get up! ')}, setAlarmClock: function setAlarmClock(time, callback) {
setTimeout((a)= > { this.getUp() const state = 'Trapped as a dog' callback(state) }, time) console.log('I set an alarm clock.${time}Wake me up after Ms. `) } } person.setAlarmClock(1000, (state) => { if (state === 'Trapped as a dog') { console.log('Sleep a little longer... ') } else { console.log('Get up now... ') } }) // I set an alarm clock to wake me up after 1000ms. person.eat() / / to eat... person.sleep() / / to sleep... // Wake up now! // Sleep a little longer... Copy the code
- When the setAlarmClock function is executed, it passes an argument called callback, which will be executed after the alarm goes off, passing the current state as an argument to the function. This allows you to get the result of the asynchronous code in the callback function and do different things based on the result.
Reference article:
Juejin. Cn/post / 684490… Es6.ruanyifeng.com/#docs/promi… Juejin. Cn/post / 684490…