I don't understand how to work with asynchronous functions.
Why does the code below stop the main thread?
async function foo() {
for (;;) {}
}
foo();
The async keyword, and promises in general, don't make synchronous code asynchronous, slow running code fast, or blocking code non-blocking.
async just makes the function return a promise and provides (with the await keyword) a mechanism to interact with other promises as if there were synchronous.
Your function starts a loop, and then just goes around and around.
It doesn't get to the end of the function, which would end the function and resolve the promise it returned.
It doesn't reach an await keyword and pause while it waits for the awaited promise to be resolved.
It just goes around and around.
If you were actually doing something in the loop which was computationally expensive and you wanted to push off into the background, then you could use a Node.js Worker Thread or a browser-based Web Worker to do it.
Putting the async keyword before the function only implies that this is asynchronous function. You need to include the keyword await before the function that you want to actually wait for. Just like this:
async function hashPin(pin){
const hashedPin = await bcrypt.hash(pin, saltRounds);
}
That's just the example from one of my projects (the redundant code has been removed before posting)
async in front of the function serves two purposes. 1. it enables usage of await in the function. 2. it tells the caller that it is guaranteed that this function returns a Promise. But neither async nor await do magically resolve blocking issues. So if bcrypt.hash has some blocking code in it, then await in front of it would not resolve that blocking issue. And removing the await and writing async function hashPin(pin){ return bcrypt.hash(pin, saltRounds).then( hashedPin => /*...*/)} would not make a difference regarding blocking.
asynckeyword isn't that.asyncfunction does not schedule is execution. It will be executed immediatly (as you can see in this fiddle ). The returned Promise is resolve at a later state.