0

My question has to do with the await purpose in node.js. I'm going to write some dummy code in order to express my question, so please don't mind if there's something missing:

let f = async function(x) {
    var data = await readFile('x.txt');
    var link = openLink(`./myfile/${data}`);
    return link;
}

So, as I understand it, f will run in a separate thread from the Nodejs Event Loop while it expects the returning 'promised' value of link. When that new thread opens, the function gets executed synchronously within that thread - but if that's true, why bother with the await? I mean, the function content is executed from top to bottom, like in any synchronous programming language, so it already naturally "waits" for readFile to complete in order to continue to the next line and use data as a parameter.

I'm surely misunderstanding something here, but as I read articles and documentation about async await it doesn't get clearer for me why the await must be there.

elanonrigby
  • 479
  • 1
  • 6
  • 14
  • 1
    "*`f` will run in a separate thread*" - no, it won't. – Bergi Jun 29 '22 at 12:40
  • This [article](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#what-is-the-event-loophttps://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#what-is-the-event-loop) might be helpful in understanding "asynchronicity" in JS. – tromgy Jun 29 '22 at 12:40
  • you need `await` to pause execution of the current function so that the awaited call can resolve the (implicit) promise that's returned by the async function. – phuzi Jun 29 '22 at 12:42
  • @phuzi by the "current function" you mean the one that has the await call, right? So when I call 'await' it resolves the 'readFile' method in a separate thread while it does something else in parallel while 'f' is paused waiting for 'readFile'? Is that it? – elanonrigby Jun 29 '22 at 12:58
  • @elanonrigby No, it pauses the execution of the function marked as `async` (`f` in your case). There is no such thing as an "await call", there is no separate thread or anything. `readFile(…)` is just any promise-returning function, `await` can wait for any promise, regardless how it was constructed. – Bergi Jun 29 '22 at 13:01

0 Answers0