DEV Community

[Comment from a deleted post]
 
pgrm profile image
Peter Grman

Ok, enlighten me. This is my understanding of JavaScript engines, and it might be completely wrong or just off for node js:

JavaScript is single threaded, with an event loop to support async operations. That means, i++ is always stable,

Console.log(i);
SyncFuncWhichDoesNotChangeI();
Console.log(i);

That code above also prints the same value twice, always. But...

Console.log(i);
await AsyncFuncWhichDoesNotChangeI();
Console.log(i);

Can print separate values for i, because it can be changed by another piece of code which jumps in while we're waiting.

If my understanding as described above is correct, than it's straight forward to design a system, which starts breaking when you remove the immediate await. It might not be as easy as in c# where even i++ isn't stable unless you lock it (or do some other stuff), but it's definitely possible. Maybe that's what you meant, that it's not an issue? Otherwise I'm intrigued to know, what node js has up it's sleeve.

Cheers

 
g1itcher profile image
G1itcher

There's a fair bit to unpack so apologies if I miss something.

Regarding database access using async/await in node: using Promise.all does not result in multiple threads (you can see this by sticking breakpoints in the methods; only one will run at a time). All you're doing with await is waiting for the asynchronous action that returns data to return its value before continuing. These two functions are functionally identical:

()=>{
  const foo = await bar();
  console.log(foo);
}

()=>{
  bar()
  .then(foo => {
    console.log(foo);
  });
}

Worth underlining that I explicitly said unrelated promises. If promises have interdependencies then yeah, they need to wait for each other.

Regarding your examples, the only way i could be changed during an await is if another callback has i in its scope and changes it. In which case, if you want i to change, you should be awaiting the promise that you expect to make that change. If you don't want i to change, don't await anything, the code is synchronous and you can safely run the rest of your code knowing that, even though you triggered some async functions, they won't resolve until the next event loop at the earliest.

If that misses your point I apologise. Do you have a more fleshed out example that we can see to try and clarify things?