Hello, I’m the pointer. Winter is coming, people also become lazy, in order to let oneself move up, I signed up for the pull hook education’s big front salary training camp. Learning needs summary, need to share, need to spur, so there is a “needle love learning front” this series, I hope you can have harvest after reading. If there is something wrong in the article, I hope you can criticize and correct me!!
Asynchronous JavaScript programming
Do the problem first, wake up your brain, successful please directly jump to the reference, failure in accordance with the order to look down
console.log(1)
setTimeout(() = > {
console.log(2)},0)
new Promise(res= > {
console.log(3)
setTimeout(() = > {
console.log(4)
res()
},0)
}).then(() = > {
console.log(5)})console.log(6)
Copy the code
1. Concept chatter, let asynchrony wait
As we all know, JavaScript is single-threaded, which was originally designed as a scripting language running on the browser. The most important operation of the browser is Dom operation. In order to avoid conflicts caused by multiple threads modifying a Dom at the same time, JavaScript adopts single-threaded.
Advantage: 46 years of People’s Republic of China, JavaScript office browser, taking a loudspeaker Shouting, I come to browser for three things: security! Safety! Or f * * king security!!
But!! It takes time to suppress bandits, it takes time to fight Huang Lords, and the people are still waiting! Unfortunately, our brothers have always been working together (there is only one thread responsible for executing code in the JS execution environment), and now there are too many time-consuming things. But Zhang is smart. We are so many brothers divided into two teams, one is called synchronous mode team, the other is called asynchronous mode team. Non-time-consuming tasks such as Posting large posters (console.log()) are done by the synchronous team, while time-consuming tasks such as going to dinner, drinking, and transferring soldiers (delay, Ajax) are done by the asynchronous team. Synchronous mode team finished, asynchronous mode team according to the length of time to do the work, first bandits, and then kill Huang Silang, we must also browser a lang Lang universe.
“Eldest brother, asynchronous has not done, in the queue”.
“No hurry, let async wait for a while!”
2. Synchronization mode
Synchronous mode means not executing together, but executing sequentially, one thing done, the next thing executed in the same order as the code was written. Specific did not say, know all understand 😀
3. Asynchronous mode
Let me start with two concepts
Event loop:
- Synchronous events are pushed, and asynchronous events await execution in the environment thread
- The synchronous event completes the stack until it finishes executing. When an asynchronous event is triggered, a message is inserted into the queue
- Read the first message in the message queue, relative to the asynchronous event pushed
- When the stack is empty and the message queue message is pulled, this is an event loop
Event Queue: A message queue stores asynchronous task messages. When an asynchronous task is triggered, a message is inserted into the message queue. When the execution stack is empty, the message in the message queue will be read
The whole process is to divide tasks first, synchronous tasks are executed in the main thread, asynchronous tasks are queued to the task queue according to the time consuming, and when the synchronous tasks are finished, they are selected from shorter ones and pushed to the main thread one by one. And so it goes on, child, child, or child
If you want to see a GIF, you can check out this guy right here
Common syntax for asynchronous operations
3.1 Event Listening
document.addEventListener('click'.function() {})Copy the code
3.2 Callback functions
I believe you see the callback function, the first thing that comes to mind is callback hell, don’t be afraid, this is how beautiful charge 😀
3.2 promise
Promise promises a state with an initial value of pending, fulfilled =>fullfilled, rejected =>rejected. When the state changes from pending, this state is locked and cannot be changed.
No second word, use it first!
// Promise is an object that accepts a function as an argument
This function takes two arguments, a resolve successful callback and a reject failed callback
// A promise can only hold one state through success or failure and cannot be changed
// Successful callbacks are fired in. Then, and failed callbacks are fired in. Catch
let p = new Promise((resolve, reject) = > {
// Use timer to simulate the interface call
setTimeout(() = > {
let randonNum = Math.random()
if( randonNum > 0.5) {
resolve(randonNum)
} else {
reject(randonNum)
}
}, 1000)
})
p.then((value) = > {
console.log(value)
}).catch((value) = > {
console.log(value)
})
Copy the code
Of course, Promise’s chain-call is the secret weapon to callback hell
let count = 1
// every call, count++
let promiseAjax = function () {
return new Promise((res, rej) = > {
setTimeout(() = > {
count++
res(count)
}, 1000 * count)
})
}
let p = promiseAjax()
p.then(value= > {
console.log(value)
return promiseAjax()
}).then(value= > {
console.log(value)
return promiseAjax()
}).then(value= > {
console.log(value)
return promiseAjax()
}).then(value= > {
console.log(value)
return promiseAjax()
})
Copy the code
There are four of Promise’s static functions that you can remember
- Promise.all([]) accepts a bunch of promises, processes them in parallel, succeeds at all, and returns a new Promise
- Promise.race([]) also accepts a bunch of promises to see who runs fast, which will be used as the end of one, can be used for interface timeout processing
- Promise.resolve() returns a Promise object whose state is determined by the given value. If the value is thenable(that is, the object with the THEN method), the final state of the returned Promise object is determined by the then method execution; Otherwise (the value is empty, a basic type, or an object with no THEN method), the Promise object will be returned with the state of FULFILLED and the value will be passed to the corresponding THEN method. In general, if you don’t know if a value is a Promise object, use promise.resolve (value) to return a Promise object so that the value can be used as a Promise object.
- Promise.reject() returns a Promise object in a failed state and passes the given failure information to the corresponding handler
Macro and micro tasks
There are two kinds of asynchronous tasks: macrotask and microtask.
Macro tasks are initiated by the JS execution environment, while microtasks are initiated by THE JS itself
Macro tasks include setTimeout, setInterval, requestAnimationFrame
Microtasks include Promise. Then. Catch. Finally, Process. NextTick, and MutationObserver
Nothing else, there are micro tasks to perform micro tasks first, and then perform macro tasks, so, now the above interview questions will be done?
3.4 the generator
There is also a generator in ES6.
The generator is a “function” that can “return” multiple times so that the value can be saved each time
Without further ado, use it first
function * foo () {
console.log("start")
let r1 = yield promiseAjax()
console.log(r1)
let r2 = yield promiseAjax()
console.log(r2)
}
// foo does not execute, only generates a generator object
// We need to call g's next method before the function is executed downward, and the execution stops at yield
// g.ext () returns an object {value: x, done: true/false} where value is the Promise reuturn value
// Done indicates the execution status of the generator. True indicates that execution is complete. False indicates that execution is not completed
// Yield only pauses function execution, but does not return. The next time the next method is executed, the function will continue to execute
let g = foo()
console.log(g)
let result = g.next()
result.value.then(data= > {
// Assign data to R1 and start the next execution until the next yield
g.next(data)
})
Copy the code
Generator function execution, if you want to finish, you have to go all the way to next(), but this is too boring, we wrapped it as a recursive function
function co (generator) {
let g = generator()
function handleResult (result) {
if (result.done) return
result.value.then(data= > {
handleResult(g.next(data))
})
}
handleResult(g.next())
}
Copy the code
3.5 async/await
Do you find the way the generator writes annoying? It doesn’t matter, the nerdy and thoughtful guy has provided us with generator syntactic candy, which is extremely simple to use and perfectly synchronous to write
async function foo () {
let r1 = await asyncFn1()
let r2 = await asyncFn2()
let r3 = await asyncFn3()
console.log(r3)
}
Copy the code
navigation
The needle to learn front-end | JavaScript depth excavation of functional programming
Needle to learn front-end | JavaScript depth excavation of asynchronous programming
Needle to learn front-end | JavaScript depth excavation of written Promise
The needle to learn ECMAScript front-end | JavaScript depth excavation
reference
All the above materials are provided by pull education big front End Boot Camp 😀