异步等待在内部是如何工作的?

3
我的问题是在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,并再次等待creditor Amount。

除异步函数外的其他执行不等待,这样可以正常工作。

  1. 第二个问题

如果对此示例使用Promise

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

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

它怎么知道?

也许我的问题毫无价值? 如果有答案,我想知道答案。

感谢您的帮助。


我的假设是错误的。 - Jaromanda X
至于async/await在内部实际上是如何工作的,我想你得查看各种JS引擎的源代码,才能确切地了解它是如何实现的。但是,为什么这很重要呢?你知道Array在内部是如何实现的吗?或者Date,甚至只是Object? - Jaromanda X
1
是的,你说得对,我想要源代码,我想知道所以才问的,就这样。 - Man
1
可能是 https://dev59.com/R1YN5IYBdhLWcg3wx6sR 的重复问题。不清楚你在第二个问题中想要问什么。 - Estus Flask
它在NodeJS和Web/Babel环境中的工作方式不同。 - Zach Leighton
2个回答

5

async-await使用生成器来解决和等待Promise。

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

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

1
如果编译器到达 let r = await first(); 并停止执行并将所有内容推入事件队列,然后在异步函数之后继续同步代码,那么为什么会有两个打印输出,而不是 b 在 2 之前打印。2 是从 first() 中打印的,它在 await 内部。 - Md Monjur Ul Hasan
请注意,@MdMonjurUlHasan,所有同步代码推入Promise内部仍然像往常一样在主线程上工作,直到触发resolve函数或*异步任务-切换到另一个线程(Web API)并将控制权返回到主线程*,例如setTimeoutDOM事件fetch APIAjax等。这就是为什么2b之前打印的原因。 - Nguyễn Văn Phong
@MdMonjurUlHasan,关于打印24的问题,那是因为Promise的主体会立即执行。至于打印b3,可以在这个答案中找到详细解释(我认为这是最好的回答,回答了你在此代码方面提出的问题)。 - OfirD

1

async/await只是一个生成器。

如果您想了解更多,请查看以下文档:

生成器

异步函数


1
生成器和异步函数之间的关系是什么? - Man
看看这篇文章,它会让你深入了解发生在引擎内部的情况......https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch4.md#promise-aware-generator-runner - Intellidroid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接