【问题标题】:How async await internally work?async await 内部如何工作?
【发布时间】:2018-11-26 08:32:41
【问题描述】:

我的问题是如何在 node.js 或 v8 中执行等待函数结果 环境。

我们知道,node.js 是单线程非阻塞 I/O 环境。

什么是内部代码以及它是如何工作的?

示例异步函数:

async function asyncCall() {      
 // `getCreditorId` and `getCreditorAmount` return promise
  var creditorId= await getCreditorId(); 
  var creditAmount=await getCreditorAmount(creditorId);

}

如果您执行此函数,则首先等待 creditorId,然后使用 creditorId 调用 getCreditorAmount,然后再次在此异步函数中等待债权人 Amount。

代替异步函数,其他执行不等待,效果很好。

  1. 第二个问题

如果在这个例子中使用 Promise

getCreditorId().then((creditorId)=>{
   getCreditorAmount(creditorId).then((result)=>{
      // here you got the result
  })
});

我的假设如果 async await 在内部使用 promise,那么 async 必须知道 getCreditorAmount 函数中使用哪个变量作为参数。

它是怎么知道的?

可能是我的问题毫无价值? 如果它有答案,那么我想知道答案。

感谢您的帮助。

【问题讨论】:

  • my assumption - 错了
  • 至于 async/await 实际上 内部是如何工作的,我想你得看看各种 JS 引擎的源代码,看看它是如何实现的- 但是,为什么它很重要?你知道Array是如何在内部实现的吗?或日期,甚至只是对象?
  • 是的,你是对的,我想要源代码,我想知道所以我问了,就是这样。
  • stackoverflow.com/questions/46908575/… 的可能重复项。不清楚您在 2 中要问什么。

标签: javascript node.js asynchronous v8


【解决方案1】:

async/await 只是一个生成器。 如果您想了解更多信息,请查看这些文档。

Generators

Async Function

【讨论】:

【解决方案2】:

async-await 使用生成器来解析并等待 Promise。

await 在 async-await 中是异步的,当编译器到达 await 时,它会停止执行并将所有内容推送到事件队列中,并在 async 函数之后继续使用同步代码。示例

function first() {
    return new Promise( resolve => {
        console.log(2);
        resolve(3);
        console.log(4);
    });
}

async function f(){
    console.log(1);
    let r = await first();
    console.log(r);
}

console.log('a');
f();
console.log('b');

由于 await 是异步的,因此在 await 之前的所有其他事情都会照常发生

a
1
2
4
b
// asynchronous happens
3

【讨论】:

  • 如果编译器到达let r = await first();并停止执行并将所有内容推入事件队列并在异步函数之后继续执行同步代码,那么,为什么要打印2,为什么不在2之前打印b。2是从first() 打印,它位于await 内。
  • @MdMonjurUlHasan 请注意,在Promise 中推送的所有同步代码仍然照常在main thread 上工作,直到点击resolve func 或async 任务-切换另一个线程(Web API)和将控制权返回给main thread,例如setTimeoutevent DOMfetch APIAjax 等。这就是为什么2b 之前打印的原因。
  • @MdMonjurUlHasan,关于打印2 然后4,那是因为the body of a Promise is executed immediately。至于b3的打印,可以阅读in this answer(我认为最好的答案是您打开的关于上述代码的question)。
猜你喜欢
  • 2021-12-18
  • 2019-12-04
  • 2020-03-09
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
相关资源
最近更新 更多