The following quotes are my primary references for understanding microtask queue processing:
Microtasks (which promises use) are processed when the JS stack empties.
That doesn't make sense to me.
One go-around of the event loop will have exactly one task being processed from the macrotask queue (this queue is simply called the task queue in the WHATWG specification). After this macrotask has finished, all available microtasks will be processed, namely within the same go-around cycle.
- Stack …
生成器的 yield 与 promise.then() 中的哪一个是理解“await”的更正确的心理模型?
属性比较,通过使用调试器逐步执行以下代码段推断:
等待:
await 不会暂停/暂停正在运行的异步函数的执行。(正在运行的异步函数“运行到完成”,当解释器遇到第一个等待时返回一个挂起的承诺。然后它会立即从调用堆栈中删除。)
await 等待承诺解决。
await expression 将函数的其余代码包装在一个微任务中。
发电机产量:
yield promise确实确保promise在执行剩余代码之前已经解决。promise.then(回调):
//promise returning function
function foo(whoCalled) {
let p = new Promise(function(resolve, reject) {
setTimeout( () => {
console.log('resolving from setTimeout - called by: ' + whoCalled)
resolve('resolve value') }, .1)
})
return p
}
//async await
async function asyncFunc() {
await foo('async function')
//rest of running function’s code…
console.log('async function howdy')
} …Run Code Online (Sandbox Code Playgroud)