异步等待内部如何工作? [英] How async await internally work?

查看:31
本文介绍了异步等待内部如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My question is how execution wait for function result in node.js or v8 environment.

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

We know, node.js is single thread non blocking I/O environment.

什么是内部代码及其工作原理?

What is internal code and how it work?

示例异步函数:

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

}

如果您执行此函数,则首先等待 creditorId,然后使用 creditorId 调用 getCreditorAmount,然后再次仅在此异步函数中等待来自 creditor Amount.

If you execute this function then first wait for creditorId then call getCreditorAmount using creditorId and again wait from creditor Amount in this async function only.

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

Instead of async function other execution not wait, that works fine.

  1. 第二个问题

如果在这个例子中使用 promise

If use promise for this example

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

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

My assumption if async await use promise internally then async must must know which varibale use in getCreditorAmount function as parameter.

它怎么知道的?

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

Might be my question is worthless? If it has a answer then i want to know the ans.

感谢您的帮助.

推荐答案

async-await 使用 Generators 来解析和等待 Promise.

async-await uses Generators to resolve and wait for Promise.

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

await is asynchronous in async-await, when compiler reach at await it stops executing and push everything into event queue and continue with synchronous code after async function. Example

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 之前的所有其他事情都照常发生

Since await is asynchronous thus every other thing before await happens as usual

a
1
2
4
b
// asynchronous happens
3

这篇关于异步等待内部如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆