Description:
Javascript is a non-blocking single-threaded scripting language;
Browser is a multi-process system to process its allocation of resources (CPU, memory), open Chrome
there will be a primary process, each open a Tab
page there is a separate process;
JavaScript synchronization task into tasks and asynchronous tasks, all the tasks are synchronized into the main execution stack (execution form a stack execution context stack), the result of waiting tasks callback enter into a task queue (task queue), until the main execution stack the task to finish before the task queue of asynchronous tasks, asynchronous tasks will be inserted into the main execution stack, will enter again next asynchronous task completes a cycle, throughout the implementation process, we called the event cycle. Task queue is divided into macro-task (macro task) and micro-task (micro tasks), in the latest standards, they are referred to as task and jobs.
macro-task probably include:
- Script (overall code)
- setTimeout
- setInterval
- setImmediate
- I / O
- UI rendering
micro-task probably include:
- process.nextTick
- Promise
- Async / Await (actually the promise)
- MutationObserver (html5 new features)
Overall execution flow chart:
async / await execution order Note:
输出:script start => async2 end => Promise => script end => promise1 => promise2 => async1 end => setTimeout
Analysis of this code:
- Executing code, output
script start
. - Execution async1 (), calls async2 (), then the output
async2 end
at this time will be retained context async1 function, and then jump out async1 function. - Encounter setTimeout, generate a macro task
- 执行Promise,输出
Promise
。遇到then,产生第一个微任务 - 继续执行代码,输出
script end
- 代码逻辑执行完毕(当前宏任务执行完毕),开始执行当前宏任务产生的微任务队列,输出
promise1
,该微任务遇到then,产生一个新的微任务 - 执行产生的微任务,输出
promise2
,当前微任务队列执行完毕。执行权回到async1 - 执行await,实际上会产生一个promise返回,即
let promise_ = newPromise((resolve,reject){ resolve(undefined)})
- 执行完成,执行await后面的语句,输出
async1 end
- 最后,执行下一个宏任务,即执行setTimeout,输出
setTimeout
新版的chrome浏览器中不是如上打印的,因为chrome优化了,await变得更快了,输出为:
而await后面跟的是一个异步函数的调用,比如上面的代码,将代码改成这样:
输出:script start => async2 end => Promise => script end => async1 end => promise1 => promise2 => async1 end setTimeout
未写完,后续待更新...