this is apparently code that hashes a password. however what does it exactly do syntactically? why does it use async and await this way? and => does not seem to define a function.
It does define a function and assigns hashPassword
to the function. It's the same thing as this:
const hashPassword = async function( password ) {
return await bcrypt.hash( password, 10 );
};
...or this (just to be clear):
const hashPassword = async function( password ) {
const hashedPassword = await bcrypt.hash( password, 10 );
return hashedPassword;
};
and also largely (for the most part) the same thing as doing this:
async function hashPassword( password ) {
const hashedPassword = await bcrypt.hash( password, 10 );
return hashedPassword;
}
...which is the same thing as this (ignoring 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 in an async function? i have an async function returning an array however when called it is received as a Promise object..
When a function is annotated with async
it wraps the return value in a Promise<T>
. Because of how types change behind-the-scenes when using async
functions in JavaScript I strongly recommend using TypeScript instead of JavaScript to avoid errors like these. Note that you can use await
with both Promise and non-Promise functions, at least.
In JavaScript, these two functions are equivalent:
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>
can you can either await
it to get T
or you use a then
function.
See here: How to return values from async functions using async-await from function?