This code appears to be for hashing a password, but the syntax is unclear. Why is async and await used in this way? And what does => signify in defining a function?
Essentially, it defines a function called hashPassword
by using async and await. You can think of it as equivalent to the following examples:
const hashPassword = async function( password ) {
return await bcrypt.hash( password, 10 );
};
...or also like this (for clarification):
const hashPassword = async function( password ) {
const hashedPassword = await bcrypt.hash( password, 10 );
return hashedPassword;
};
It's quite similar to doing this as well:
async function hashPassword( password ) {
const hashedPassword = await bcrypt.hash( password, 10 );
return hashedPassword;
}
...which can be boiled down to this if we ignore error-handling with rej
:
function hashPassword( password ) {
return new Promise( ( res, rej ) => bcrypt.hash( password, 10 ).then( h => res( h ) )
}
How do you return a value from an async function? I have an async function that returns an array but when called, it is received as a Promise object.
When using async
, the function wraps its return value in a Promise<T>
. To avoid such issues, it is recommended to use TypeScript instead of JavaScript due to these type changes. Remember that you can use await
with both Promise and non-Promise functions.
In JavaScript, these two functions are essentially the same:
async function foo() {
const v = await anotherAsyncFunction();
return v;
}
function foo() {
return new Promise( function(resolve,reject) {
anotherAsyncFunction().then( v => resolve( v ) );
} );
}
When a function returns a Promise<T>
, you can either await
it to get T
, or you can use the then
method.
For more information, check out: How to return values from async functions using async-await from function?