Sorry for this naive question.
Reading some existing JavaScript I see a function with code like ...
async function _load() {
await ensureDir(path);
return await readFile(filename);
}
... why not use readFileSync
instead, what's the difference?
When you call await (e.g. in Node.js) does other code become runnable, including e.g.:
- Other code which went to sleep by calling
await
- Code scheduled using e.g. setTimeout
If so I guess you must worry about the same kind of thing you worry about in multi-threading, e.g. ...
- Updating state might require writing to several files
- You might await after writing one file
- Another "thread" might wake up, read the files, and find them in an inconsistent / partially-updated state
... is that so?
The difference being only or mainly that, unlike with threads, there are limited places where a thread-switch might occur -- i.e. only when you explicitly call await
.
I have tried Google for an answer. The tutorials I've found tell me what happens to my code when it calls await but doesn't tell me (doesn't confirm) explicitly what other code might become runnable when it awaits. I've read that "there's a JavaScript event loop", and that, "JavaScript is single-threaded", but I don't know how await
fits into that. The above is my guess as to how it works, I hope you can confirm my guess is correct, or correct it, or reference a tutorial which touches on this topic.
readFileSync
is blocking, whereasawait readFile
yields control so that other things can be happening while you wait. See e.g. stackoverflow.com/questions/47939680/…