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

Exploring the Information Within HTML Forms

When my HTML form sends data to the server, it looks like this: { r1: [ '1', '2', '3' ], r2: [ 'Top', 'Greg', 'Andy' ], r3: [ 'validuser', 'invaliduser', 'validuser&a ...

Turn off error notifications from eslint parsing

Within my code, there is a conditional export that looks like this: if (process.env.NODE_ENV === 'testing') export myFunc; While in es6, this type of statement is typically not allowed due to the requirement for imports and exports to be top- ...

Creating a REST API with user-specific authorization: A step-by-step guide

Currently, I am in the process of developing a REST API backend server for my web application using NodeJS, ExpressJS, and MySQL as the database. My main concern lies in implementing authorization to prevent User A from accessing or modifying another user& ...

Guide on how to trigger a pop-up modal to open a new webpage by clicking on a hyperlink

I have a page called one.html that has a link on it <a href="#">Click to open second page<a/> When this link is clicked, I would like for second.html to open in a popup modal. The second page contains a basic table that I want to di ...

Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. ...

In React, components will consistently render the initial code

I have a chat application that requires authentication and uses cookies. Here's what I've been attempting: class AppHeader extends React.Component { constructor(props) { super(props) } render() { if (cookies.get(' ...

express: how to differentiate routing path based on request parameters

Currently, I am working on an API that is designed to receive a specific value from an Android client and then provide back a list of posts. One interesting aspect of this API is the request value known as req.body.sortType, which influences how the list o ...

The absence of a defined window - react-draft-wysiwyg integration with Next.js (SSR) is causing issues

Currently, I am in the process of developing a rich text editor that is used to convert plain HTML into editor content using Next.js for SSR. While working on this project, I encountered an error stating "window is not defined," prompting me to search for ...

Having trouble with deploying my Nodejs App on Heroku, it keeps crashing

I have a straightforward Nodejs application that is functioning perfectly when run locally, but for some reason Heroku is having issues running it correctly: Process exited with status 130 2015-09-19T15:56:22.872647+00:00 heroku[router]: at=error code=H1 ...

What is the process for uploading a package to a repository using webpack?

Currently working on a NodeJs project where webpack is being used for packaging. In the past, I utilized pom.xml for packing and deploying artifacts to repositories using distributionmanagement. Looking to set up a Webpack task for deployment now. Is it ...

Utilizing a custom function declared within the component to handle changes in Angular's ngOnChanges

Although it may seem like a simple question, I'm struggling to find a solution. Here's the issue at hand: In my Angular Component, there's a function that I need help with. export class RolesListComponent implements OnInit, OnChanges { ...

Unable to find the view titled "/landing.ejs" in the specified views directory

While working in Cloud9, I encountered an error when attempting to run the application. The error message states: "Failed to lookup view "/landing.ejs" in views directory." Here is my code snippet: var express = require("express"); var app = express(); a ...

Can you add a variable to a string once the string has already been formed?

Is there a way to change the quotes of a string from double or single quotes to backticks in JavaScript after it has already been defined? I need to be able to add variables into the string. I attempted using replace(), but it seems like the variable is n ...

Error: The socket.io client script cannot be found when using Express + socket.io

This situation is really getting to me... even though I have a functioning version of Express + Socket.io, I can't replicate it in a new project folder with standard NPM installs. Can someone please help me figure out what I'm doing wrong...? Her ...

I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below. function sort(nums) { function minIndex(left, right) { ...

Automate the login process for a website and programmatically fill out and submit a form

I am currently trying to automate the login process on Skype's website using Selenium in C#. Everything goes smoothly until I reach the password field, which seems to be elusive to Selenium. I have tried various methods to locate the password field bu ...

Issue with using jQuery and parseDouble

I have been dealing with an AJAX request that retrieves a JSON object containing multiple values, each with two decimal points. However, the issue is that when these values are returned as part of the JSON, they are in string format. My goal is to perform ...

Can jQuery be used to target pseudo elements such as scrollbars for selection?

Can you use jQuery to target pseudo elements like these: ::-webkit-scrollbar ::-webkit-scrollbar-track ::-webkit-scrollbar-thumb Is it possible to manipulate them through jQuery? #scroller { background: #fff; height: 300px; wid ...

Push function is not available in Redux

Currently, I am facing an issue while trying to use the state of a component in other components. Since this state needs to be accessed by multiple components, I have decided to switch to Redux. However, I encountered an error 'newUsers.push is not a ...

Instructions on keeping a numerical counter at its current value for all site visitors

Recently, I integrated a number counter into my website. However, I am facing an issue where the count resets to zero whenever a new visitor accesses the site. I'd like the count to remain persistent and update based on the previous count. For instanc ...