小编Ano*_*nEq的帖子

Why does this line of code with 'await' trigger microtask queue processing?

The following quotes are my primary references for understanding microtask queue processing:

Microtasks (which promises use) are processed when the JS stack empties.

- Jake Archibald

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 …

javascript asynchronous event-loop promise

11
推荐指数
1
解决办法
795
查看次数

Javascript 异步函数“await”的正确心理模型:生成器的“yield”与“promise.then()”?

生成器的 yield 与 promise.then() 中的哪一个是理解“await”的更正确的心理模型?

属性比较,通过使用调试器逐步执行以下代码段推断:

等待:

  1. await 不会暂停/暂停正在运行的异步函数的执行。(正在运行的异步函数“运行到完成”,当解释器遇到第一个等待时返回一个挂起的承诺。然后它会立即从调用堆栈中删除。)

  2. await 等待承诺解决。

  3. await expression 将函数的其余代码包装在一个微任务中。

发电机产量:

  1. yield 暂停正在运行的函数的执行。生成器函数不会“运行完成”。
  2. yield promise确实确保promise在执行剩余代码之前已经解决。
  3. yield 不会包装或创建微任务。

promise.then(回调):

  1. 不会暂停正在运行的函数的执行。
  2. 在执行回调之前等待承诺解决。
  3. 创建一个微任务(回调)

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

javascript event-loop node.js promise async-await

5
推荐指数
2
解决办法
961
查看次数