"Resulting in 'undefined' due to an asynchronous function call

Encountering an issue with async method implementation.

In my authServices, there is a loginWithCredential function which is asynchronous:

async loginWithCredential(username, password){
    var data = {username: username, password: password};
    api.post('/api/users/login', data)
        .then(successCallback, errorCallback)

    function successCallback(response) {
        return response.data;
    }

    function errorCallback(error){
        console.error(error);
        return false;
    }
}

Within my store, I am attempting to retrieve the data:

@action login (user, password) {
    this.isAuthenticating = true;
    // Additional code above, focusing on setting token here
    return authServices.loginWithCredential(user, password).then(function(response){
        console.log(response);

    },function(response){
        console.log(response);
    });
}

The issue lies in the fact that the response in my store is consistently undefined as it is executed before the service has completed its return. Any suggestions on how to address this?

Answer №1

async authenticateUser(username, password) {
    var userCredentials = {username: username, password: password};
    const {userData} = await api.post('/api/users/login', userCredentials)
    return userData;
}
@action async verifyLogin (user, password) {
    this.isAuthenticating = true;
    // additional code here to handle token
    return await authenticationServices.authenticateUser(user, password)
}

Remember to use await in your async functions. If not, make sure to return a promise.

In the login function, please do not attempt to return within a callback function as it is out of context and will not return a value.

Answer №2

In order to properly use async/await in your code, make sure to include the await keyword with functions marked as async. The await keyword can only be used within a function that has been labeled as async. Here is an example of how you can implement this:

async loginWithCredential(username, password){
    var data = {username: username, password: password};
   await api.post('/api/users/login', data)
        .then(successCallback, errorCallback)

    function successCallback(response) {
        return response.data;
    }

    function errorCallback(error){
        console.error(error);
        return false;
    }
}

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

Sending an array of functions to the onClick event of a button

Having difficulty with TypeScript/JavaScript Currently working with an array of functions like this private listeners: ((name: string) => void)[] = []; Successfully adding functions to the array within another function. Now looking to trigger those ...

Beneath the Surface: Exploring Visual Studio with NPM and Typescript

Can you explain how Visual Studio (2015) interacts with external tools such as NPM and the Typescript compiler (tsc.exe)? I imagine that during the building of a solution or project, MSBuild is prompted to execute these additional tools. I'm curious a ...

Implying generics at a later time, not during instantiation / altering the type of a generic

If we consider the example provided, is there a way to instruct the typescript compiler that the return type of baz must be string, since it can be inferred from foo.a('aString') that it's a string? const fn = <T,S>()=>{ let s: S ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Struggling with getting Typescript async/await to function properly

I'm experiencing an issue with async/await in TypeScript targeting es2017. Here is the code snippet that's causing trouble: My route.ts : method: 'POST', config: { auth: { strategy: &apo ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...

Guide to leveraging tanstack table v8 for sorting data within a specific date range

Received data from API: const abc = [ { date: '2023-12-8', value: 'mop' },{ date: '2023-10-8', value: 'qrs' } ] How can we create a date range using two input fields when the dates are in string forma ...

What are the steps for implementing the ReactElement type?

After researching the combination of Typescript with React, I stumbled upon the type "ReactElement" and its definition is as follows: interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor< ...

What strategy does Node recommend for organizing code into multiple files?

In the midst of my current project, which involves NodeJS and Typescript, I am developing an HTML5 client that communicates with a NodeJS server via web-sockets. With a background in C#, I prefer to organize my code into separate files for different functi ...

Issue concerning props and renderItem within react native's flatlist encountered

I am currently working on a basic project in react native to get familiar with everything before I start my main project. The main objective of this project is to display an array using a flatlist, but the challenge is to modularize it gradually (e.g. sto ...

What is the best way to restrict string patterns in TypeScript?

I have a type definition that looks like this: type ActionType = 'TypeA' | 'TypeB' | 'TypeC' | 'TypeD'; I need myActionType to be a string that is either one of the ActionTypes or a combination of ActionTypes separa ...

Jasmine: utilizing unit test to spy on the invocation of a nested function

When running unit tests for an Angular app, I need to spy on a function called func1 to check if it is being called. However, within func1 there is a call to func2 and I also want to spy on that to see if it is being called. How should I structure my unit ...

Revamp the switch-case statement in JavaScript code

Is there a way to refactor this code in order to prevent repeating dailogObj.image? I would have used a return statement if it wasn't for case 5 where two assignments are required. getDialogData(imageNum): any { const dailogObj = { image: ...

Struggling to identify the error while utilizing Jasmine's throwError function

I am relatively new to using Jasmine and have been experimenting with the toThrowError() function. However, I can't seem to get my test to pass successfully. In one of my functions, I purposely throw an error: test.service.ts test(list:{}){ if ...

The datatype 'string' cannot be assigned to the datatype '(token: string) => void'

Within my Angular2 application, I have a class that includes several properties which will be assigned values within components. @Injectable() export class Globals { private token: string; private authorization: string; private roleUser: boole ...

Retrieve data from a JSON object within an HTML document

How do I display only the value 100 in the following div? <div> {{uploadProgress | async | json}} </div> The current displayed value is: [ { "filename": "Mailman-Linux.jpg", "progress": 100 } ] Here is my .ts file interface: interface IU ...

Retrieving the event name from a CustomEvent instance

Looking to retrieve the name of a CustomEvent parameter in a function, which is basically the string it was created with (new CustomEvent('foo')) If you need a reference, check out https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent ...

React's componentDidUpdate being triggered before prop change occurs

I am working with the CryptoHistoricGraph component in my app.js file. I have passed this.state.coinPrices as a prop for this element. import React from 'react'; import axios from 'axios'; import CryptoSelect from './components/cry ...

What is the best way to transfer an array of objects between two components in React?

I've exhausted all the solutions found online, but I'm still facing a persistent issue. Despite my efforts, whenever I try to log information in another component, it keeps showing as undefined. (Just to clarify, the data being dealt with is an ...

Utilizing Props to Manage State within Child Components

Is it possible to assign the props received from a Parent Component as the state of a Component? export default class SomeComp extends Component { constructor(props) { super(props); this.state = someProps; // <-- I want to set the ...