简体   繁体   中英

Behavior of synchronous function call vs “await” on async function call

Certain Node.js modules (both built-in and otherwise) provide synchronous and asynchronous versions of the same functionality (either via callbacks or promises). For example, the bcrypt module provides bcrypt.hash() that returns a promise and computes the hash asynchronously, or bcrypt.hashSync() that returns a hashed value directly.

However, sometimes work can't proceed until this async action is done, which is what await is for. Given that, what is the difference between these two code snippets, and which one of these would be the recommended way?

const bcrypt = require('bcrypt');

// method 1
const hash1 = bcrypt.hashSync('password123', 10);
console.log(`hashed password: ${hash1}`);

// method 2
(async function() {
    const hash2 = await bcrypt.hash('password123', 10);
    console.log(`hashed password: ${hash2}`);
})();

The first one has less fluff (no async/await keywords), and given that I'm awaiting the response of bcrypt.hash() anyway, I don't know if there is a performance benefit to async here. Is there anything I'm missing?

An async function, once it reaches an await , will immediately hand control over to the JS scheduler. It does not actually "wait" for anything, instead it lets the JS scheduler do whatever it needs to, letting other code run, knowing that at some point in the future it's going to get a signal that allows it to resume. The performance benefit is mostly when you have other code that can run completely independent of this code. If so: yes, await is going to make things far more performant. However, if this is your only code... then no, there is no reason to use async/await

The main point of asynchronous version of bcrypt.hash() is to free up the thread for other processes/tasks that do not require the result/return value of the bcrypt.hash() .

So that would be helpful if you have other functions/handlers that might need to run before the hash() function is done. If that is the case, then the asynchronous bcrypt.hash() gives you better performance. But like @Mike 'Pomax' Kamermans mentioned, if you don't have any other processes that are independent on this result, then the synchronous bcrypt.hashSync() is perfectly fine.

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