3

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.

hong4rc
  • 3,999
  • 4
  • 21
  • 40
Man
  • 742
  • 1
  • 6
  • 23
  • 1
    [your async/await code in babel transpiler](http://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=IYZwngdgxgBAZgV2gFwJYHsI1JKBhYAG0IAoBKGAbxhtoCgYB6RmAAwHMBTZPAJ04AmqZOl4BJAa2wQBbLj35CRvAIIBbdEmRT-yBLywAHXujWoQnBjABuwXjCiLhoiQF5sAd2DCY8voOdxAXIAbhgrW3tHAOR1TQhkV2AvHz8nZTitEmilFwEyELo6AF8gA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=true&fileSize=false&sourceType=module&lineWrap=true&presets=env&prettier=false&targets=&version=6.26.0&envVersion=1.6.2) – Jaromanda X Jun 17 '18 at 03:50
  • `my assumption` - is wrong – Jaromanda X Jun 17 '18 at 03:51
  • as for how async/await **actually** works internally, I guess you'd have to look at the source code of the various JS Engines, to see exactly how it is implemented - but, why is it important? Do you know how Array is implemented internally? Or Date, or even just Object? – Jaromanda X Jun 17 '18 at 03:56
  • 1
    yes you are right i want source code ,i want know so i asked ,thats it. – Man Jun 17 '18 at 04:02
  • 1
    Possible duplicate of https://stackoverflow.com/questions/46908575/async-await-native-implementations . It's unclear what you're asking in 2. – Estus Flask Jun 17 '18 at 04:03
  • Also it works differently in NodeJS vs. a web/babel environment – Zach Leighton Jun 17 '18 at 06:10

2 Answers2

5

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
NAVIN
  • 3,193
  • 4
  • 19
  • 32
  • 1
    if the compiler reaches `let r = await first();` and stops executing and push everything into event queue and continue with a syncronous code after async function, then, how come 2 prints, why not b prints before 2. 2 is printed from the `first()`, which is inside the `await`. – Md Monjur Ul Hasan Jul 22 '19 at 04:03
  • @MdMonjurUlHasan Pls note that everything sync code push inside `Promise` still working on `main thread` as usual till hit `resolve` func or *async tasks - switch another thread (Web API) and return control to `main thread`* like `setTimeout`, `event DOM`, `fetch API`, `Ajax`, etc.. . So that is the reason why `2` prints before `b`. – Nguyễn Văn Phong Jan 02 '21 at 04:05
  • @MdMonjurUlHasan, regarding the printing of `2` and then `4`, that's because [the body of a Promise is executed immediately](https://stackoverflow.com/questions/42118900/when-is-the-body-of-a-promise-executed). As for the printing of `b` and then `3`, a thorough can be read [in this answer](https://stackoverflow.com/a/42043784/3002584) (which I think best answers the [question](https://stackoverflow.com/q/57139161/3002584) you opened regarding the above code). – OfirD Jun 08 '21 at 17:21
1

async/await is just a Generator. Take a look at these docs if you would like to learn more.

Generators

Async Function

Intellidroid
  • 1,053
  • 1
  • 9
  • 15
  • what is relation between generator and async function – Man Jun 17 '18 at 11:30
  • Take a look at this article as it will give you a good insight into what is going on under the hood......https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch4.md#promise-aware-generator-runner – Intellidroid Jun 17 '18 at 18:00