This afternoon saw a lot of questions about the execution order through their own practice finally understand the record about
Take frequent online code is:
async function async1() {
console.log('async1 start');
await async2();
console.log('asnyc1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(() => {
console.log('setTimeOut');
}, 0);
async1();
new Promise(function (reslove) {
console.log('promise1');
reslove();
}).then(function () {
console.log('promise2');
})
console.log('script end');
Then is the result:
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
understanding:
js event in two ways: macro task (macro task) and micro-tasks (micro task)
Macrotask comprising: script (script code is read, too, is executed task) setTimeout setInterval
Micro tasks include: promise.then ( note the promise.then ), process.nextTick
Event execution order: first execution of the macro task, and then perform micro tasks
Task execution order: first synchronization code execution, after the implementation of asynchronous code
Synchronization code, what does the above code:
console.log('script start');
async1();
console.log('async1 start');
console.log('async2');
console.log('promise1');
console.log('script end');
It is noteworthy that
1. async function declaration
If you do not like plain functions await
If there is the code prior to await await await include keeping this function is performed synchronously
After await execution async2 this function await let out a thread, the return of the promise to join the micro asynchronous task queue, so async1()
the following code should wait to continue after completion of the above;
(Own understanding:
Since the above-described code has not been performed before performing new Promise async2 so will not add to the asynchronous task micro promise.then the queue
Good hands of a small partner may try to put that code into the new Promise async1 (); will return now before the execution order is not the same
)
2. new Promise () statement is immediately executed, promise.then is asynchronous;
Then the asynchronous code:
promise.then
setTimeout
These are their own practice ➕ understanding if not, please correct the god
async function async1(){
console.log('a1 start');
await async2();
console.log('a1 end');
}
async function async2(){
console.log('async2');
}
new Promise((resolve) => {
console.log('promise1');
resolve();
}).then(() => {
console.log('promise1 then');
});
async1();
new Promise((resolve) => {
console.log('promise2');
resolve();
}).then(() => {
console.log('promise2 then');
});
Execute this code you will find that delicate relationship between promise.then and await