Can you please explain the meaning of this statement in JavaScript/Node.js with regards to the importance of the => operator and the async and await keywords being used here?

(1) This snippet of code is used to hash a password, but the syntax may be unclear. Why does it utilize async and await in this manner? And why doesn't the => symbol seem to define a function?

const hashPassword = async password => await bcrypt.hash(password, 10)

(2) How can you properly return a value from an async function? I have an async function that returns an array, but when I call it, the value is received as a Promise object.

async function agentName() { 
  // ...
  return anArray;
}

let data = agentName();
console.log("In callback. Data is " + data);

Output:

In callback. Data is [object Promise]

Is the issue with how I've defined the function/return value or how I'm calling the function?

Answer №1

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?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Successful AJAX Post request functioning exclusively within the Web Console (Preview)

When a user clicks on an element on the website, I have a simple AJAX request to send the ID of that element. However, the script only works in the Web Console under the Network -> Preview section and this issue occurs across all browsers. Here is the cod ...

Having trouble with React throwing a SyntaxError for an unexpected token?

Error message: Syntax error: D:/file/repo/webpage/react_demo/src/App.js: Unexpected token (34:5) 32 | 33 | return ( > 34 <> | ^ 35 <div className="status">{status}</div> 36 <div className=&quo ...

Utilizing the NuxtJS framework to tap into video camera functionalities

I am completely new to Vue and NuxtJs. My goal is to create a webcam feature using NuxtJs, but I have encountered some challenges. <template> <div class="photobooth"> <div class="controls"> <button @click="takePhoto">Ta ...

I am seeking the original XML element with the exact tagName, including proper case sensitivity

Below is a code snippet that retrieves and displays the UpperCase text of tagNames. I am looking to work with the original case. var xml = '<myElements type="AA" coID="A923"><myHouse>01</myHouse> <myCars>02</myCars><m ...

Executing the npm install command on an Ubuntu server using Octopus Deploy software

We have implemented Octopus deploy for deploying an angularjs application. During the post deployment process, when I attempt to run a bash script that includes npm install, I encounter an error: npm: command not found Interestingly, if I log in to the L ...

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...

Utilize express.router() to send a get request to a third-party API while including an API key

As I develop my react application, I am faced with the task of retrieving data from a third-party site that requires me to include an API key in the header as 'X-Auth-Token'. Currently, I am using the fetch() API from the client-side JavaScript ...

Unable to successfully retrieve a PDF file (stored as binary data) from Mongo-db using React JS technology

I integrated the express-fileupload library for uploading a PDF file to MongoDB, but I am encountering an issue while trying to download the same file on the front end. Upon downloading the PDF, I receive the following error message: "Error. Failed t ...

Placing a JavaScript button directly below the content it interacts with

I am currently working on a button that expands a div and displays content upon clicking. I am facing an issue where I want the button to always be positioned at the bottom of the div, instead of at the top as it is now, but moving it within the parent div ...

Exploring ways to create additional file upload fields with distinct names through JavaScript

My latest project involved creating a button that allows users to add a file upload field, a separate button to remove a file upload field, and a counter to keep track of the total number of file upload fields. However, it appears that the fields are not b ...

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...

When utilizing Expo, importing a module may result in returning null

I've been attempting to incorporate a compass module into my project using expo and react native, but I'm encountering some issues. Check out the library here The problem arises when I try to import the module. Here's the error message I r ...

What is the best method for navigating and passing data in dynamic routing with NEXT.JS?

In the process of developing my next.js ecommerce app, I am utilizing Firebase to fetch product data. My goal is to have users click on a product and be redirected to a new page displaying the details of that particular product. However, despite using the ...

Reduce the use of javascript by incorporating NPM specifically after publishing instead of during the building process

My goal is to minify JS files using NPM commands, but I want the minify command to only run after Post Publish and not on Build. Unfortunately, it currently runs after both build and publish. In my Package.json file, I have the following code: "scripts" ...

What is the best way to perform a multi-link latency check, display the ping results, and use JavaScript to determine the fastest URL?

click here for image description I have noticed that many websites offer this feature, making it easier for users to choose the best URL or server based on their location. As a JavaScript novice, I'm wondering if someone could demonstrate how this is ...

Can you provide me with the URL for the jQuery post function?

Could someone please clarify which URL I should use in the $.post call to the server for a node.js file? Most tutorials demonstrate with PHP files, but I'm unsure about calling node.js files. Should I post it to the app.js file or the route file? Thi ...

Manipulate JQuery plug-in properties within an AJAX request using MVC

Currently, I am utilizing a Jquery time picker sourced from Within the view, there exists this time picker control. $("#startTime").timePicker({ startTime: "09.00", endTime: new Date(0, 0, 0, 19, 0, 0), show24Hours: false, ...

When displaying content within an iframe, toggle the visibility of div elements

I'm attempting to toggle the visibility of certain page elements based on whether the page is loaded in an iframe. <script>this.top.location !== this.location && (this.top.location = this.location);</script> The above code succes ...

Is there a way for me to record the variable's name instead of its linked data?

Currently, I am developing a node.js program that monitors the prices of different currencies. While I can successfully retrieve the prices, I would like the program to also display the names of the currencies along with their prices. In the code snippet b ...

Could it be that not all requests are answered when using Node-LokiJS? Is the status of the request always stuck in

A tutorial I followed on file upload with multer-express also covered retrieving images by id at Scoth.io. The database setup utilizes LokiJS. While most of the APIs are functioning properly, there seems to be an issue with the API to retrieve multiple i ...