Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How async await internally work?

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

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

What is internal code and how it work?

Example async function:

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

}

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. Second question

If use promise for this example

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

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

How it know ?

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

Thanks for help.

like image 551
Man Avatar asked May 05 '26 21:05

Man


1 Answers

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

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');

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

a
1
2
4
b
// asynchronous happens
3
like image 121
NAVIN Avatar answered May 08 '26 11:05

NAVIN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!