Don’t look at it. It’s not finished. /
It all started with the fact that I wanted to use async/await in my project, but god forgave me and failed, so I completely rebuilt my cognition. There’s a question on the Internet that’s really helpful, so I’ll just use it. 👇
async function async1() {
console.log( 'async1 start' )
await async2()
console.log( 'async1 end' )
}
async function async2() {
console.log( 'async2' )
}
console.log( 'script start' )
setTimeout( function () {
console.log( 'setTimeout' )
}, 0 )
async1();
new Promise( function ( resolve ) {
console.log( 'promise1' )
resolve();
} ).then( function () {
console.log( 'promise2' )
} )
console.log( 'script end' )
Copy the code
Do not press F12, paste code, while reading the article while looking at the code, will high😄
1.3.1 If you want to find the right answer to this question, you need to know the following three things
- JavaScript event loops, call stacks, and task queues
- promise
- If you can understand async await, then skip section 1.3.1 and continue reading if you don’t understand anything.
#####1.3.1.1 JavaScript event loops, call stacks, and task queues (also called callback queues)
- First, JavaScript is single-threaded, meaning that only one task can be executed at a time
- Tasks can be divided into synchronous tasks and asynchronous tasks look at the code
console.log(1);
setTimeout(function(){console.log(2); }, 0); console.log(3);Copy the code
What does this output? One, three, two. Why? See below
-
Log (‘1’), console.log(1); Log (1) Is pushed out of the stack after execution
-
Perform setTimeout (function () {the console. The log (2); }, 0); If you find that this is an asynchronous task, put it aside and put it in another module. In other modules, after 0 seconds, it enters the task queue and waits for it to enter the call stack
-
Perform the console. The log (3); console.log(3); Log (3) is pushed out of the stack after execution
-
Perform setTimeout (function () {the console. The log (2); }, 0); The same is done after the completion of the stack
Promise segmentfault.com/a/119000001… Segmentfault.com/a/119000000… Es6.ruanyifeng.com/#docs/promi… Segmentfault.com/a/119000001… Blog.csdn.net/corner2030/… Segmentfault.com/a/119000001…