async/await、promise、setTimeout

Event loop:

js event is divided into macro tasks and micro tasks , macro task for the script, setTimeout, setInterval; micro-tasks as Promise.then, process.nextTick;

Event execution order is the first task to execute the macro, micro and then put all the tasks executed, execution of the macro task again, this cycle.

Task into synchronization task and asynchronous tasks ;

Event loop that is: synchronization tasks directly into the main thread, asynchronous tasks go to the registration event list, and then back to the message queue waiting for synchronization events after the implementation, reads the list of events in the asynchronous task execution into the main thread

 

async function declaration will define a return AsyncFunction object asynchronous function.

When async function returns a value, resolve method Promise will be responsible for delivering this value; when the async function throws an exception, reject method Promise will pass this abnormal values.

await processing result is returned Promise object. If the wait is not Promise object, the return value itself.

promise to return the object async, will first encounter await the return, after triggering the asynchronous functions finished first, followed by execution.

Promise Although it is a function of immediate execution, but resolve callback is executed asynchronously. So, resolve () callback will be placed in a queue, when the implementation when resolve (), the task will be placed in the message queue, waiting for the call stack free time cycling event again removed it.

 

A classic face questions in mind:

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') 

Of course, is printed script start, then began calling async1 function, print async1 start, enter async2 function, print async2, finished enables asynchronous copy, Promise because it is executed immediately, so enter the new Promise, print promise1, resolve is an asynchronous so advanced message queue waiting to print script end, after the implementation of relosve has been waiting for a print promise2, asynchronous ends, the print async1 end, because setTimeout macro task, the final execution, print setTimeout.

The correct answer is:

script start
async1 start
async2
promise1
script end
promise2
async1 end
setTimeout

 

Guess you like

Origin www.cnblogs.com/aruanmei/p/12449127.html