Why is my infinite loop blocking when it is in an async function? [duplicate]

末鹿安然 提交于 2019-11-28 13:11:05

The async keyword doesn't make synchronous code asynchronous, slow running code fast, or blocking code non-blocking.

It 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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!