简体   繁体   中英

Bcryptjs - using synchronous vs. asynchronous solutions?

I am trying to implement a simple login/authentication app and I am using bcryptjs in order to salt/hash the user's password before putting it in the database. In the documentation it offers a synchronous way of hashing the password and an asynchronous way. I guess my question is how do I know whether the asynchronous or synchronous version is right for my application and what should I be considering when deciding whether to implement a synchronous or asynchronous solution?

In general asynchronous tasks are preferred over synchronous to increase user interaction with the application. Synchronous tasks are executed in the order the line of code is written, hence blocks the thread assigned for processing. Since JavaScript is single threaded, the whole event loop is blocked.

Same goes with bcrypt, as has been explained in their documentation :

Why is async mode recommended over sync mode?

If you are using bcrypt on a simple script, using the sync mode is perfectly fine. However, if you are using bcrypt on a server, the async mode is recommended. This is because the hashing done by bcrypt is CPU intensive, so the sync version will block the event loop and prevent your application from servicing any other inbound requests or events. The async version uses a thread pool which does not block the main event loop.

I always choose asynchronous when it is available because it allows you to dispatch multiple tasks (practically) simultaneously. However, in this case (authentication), it may seem like it doesn't matter (because authentication must be completed anyway before your other code should aquire further private data).

A question to ask is: What else do you need to do while authentication is pending? If you can think of something that could be done, while authentication is pending, that's where asynchronous really shines, because you'd be able to do that thing during the latency of the authentication.

If you choose asynchronous, make sure you understand how promises work and I'd use await to make other portions of your script wait on that authentication-promise to resolve directly to a variable. If you don't know about these things, and are in hurry, only then would I settle for using synchronous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM