Encountering difficulty obtaining return value from asynchronous function, await behaving inconsistently in Vue API Service

I am in the process of developing a new service to interact with my API. I am not very familiar with async/await, but I have encountered a puzzling issue that doesn't seem to align with what I've read in the documentation.

When attempting to use await to retrieve the result from an async function (UserAuthService.login), I receive the error message: " 'await' expression is only allowed within an async function"

The problem occurs within the Login component when trying to fetch the result. If the login function is indeed an async function, why am I encountering this error? How can I effectively retrieve the result from the async function?

auth_user_service.ts:

const UserAuthService = {
  /**
     * Authenticate the user and save the access token to TokenService.
     *
     * @returns success
    **/
  login: async function (email: string, password: string): Promise<boolean> {
    const requestData = {
      method: 'POST',
      url: 'auth/token/',
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json;charset=UTF-8'
      },
      data: {
        client_id: process.env.VUE_APP_APPLICATION_CLIENT_ID,
        client_secret: process.env.VUE_APP_APPLICATION_SECRET,
        grant_type: 'password',
        username: email,
        password: password,
        scope: 'read write'
      }
    }

    try {
      const response = await ApiService.customRequest(requestData) // just return axios(data);


      if (response.status == 200) {
        return true;
      } else {
        return false;
      }

    } catch (error) {
      return false;
    }
  },
}

Login.vue:

<template>...</template>
<script lang="ts">

import { UserAuthService } from '../services/auth/auth_user.service'

export default {
    data: () => ({
        form: {
            email: '',
            password: ''
        },
    }),
    methods: {
        login():void {
            let success: boolean = await UserAuthService.login(this.form.email, this.form.password); //error here
            console.log(success)

        }
    } 
};
</script>

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": false,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "typeRoots": [
      "node_modules/@types",
      "src/types"
    ],
    "types": [
      "webpack-env",
      "jest",
      "vuetify"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Answer №1

When utilizing the await keyword within a method, it is crucial to declare the method as async:

methods: {
    async login(): Promise<void> { // added async, changed return type
        let success: boolean = await UserAuthService.login(this.form.email, this.form.password);
        console.log(success)
    }
}

Furthermore, bear in mind that with the addition of the async keyword, the method now returns a Promise. In TypeScript, it is necessary to adjust the returning type from void to Promise<void>.

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

Error NG8001: The element 'router-outlet' is not recognized: Make sure that 'router-outlet' is a component in Angular, and confirm that it is included in this module

Having trouble running ng serve or ng build due to an error message stating that 'router-outlet' is not a recognized element. The Angular application structure looks like this: app.module.ts: import { NgModule } from '@angular/core'; i ...

Opening and closing a default Bootstrap modal in Angular 2

Instead of using angular2-bootstrap or ng2-bs3-modal as recommended in the discussions on Angular 2 Bootstrap Modal and Angular 2.0 and Modal Dialog, I want to explore other options. I understand how the Bootstrap modal opens and closes: The display pro ...

Using the .json method in Angular 7 for handling responses

While attempting to implement the function getProblems to retrieve all problems within its array, I encountered an error message appearing on res.json() stating: Promise is not assignable to parameters of type Problem[]. It seems that the function is ...

Using the React Hook useEffect may lead to the creation of duplicate objects when updating state

I'm facing an issue with a component in my project. I am making multiple calls to an external API and receiving values inside objects. The goal is to add each of these object returns to the state. However, I am encountering a problem where duplicate o ...

Minification of CSS - Vuetify

While working on my Nuxt project with Vuetify, I noticed that the page source is quite lengthy with 26k lines of code, most of which is generated by Vuetify's CSS. On comparing it with other pages, I see shorter code with difficult-to-read CSS. Is the ...

Having difficulty deciphering the legend in the Highcharts library for Angular (angular-highcharts)

I have a requirement to display two datasets as dual column charts. (2) [{…}, {…}] 0: historyDate: "2021-02-10T10:00:000Z" documentStatusHistory: CANCELLED: 6 COMPLETED: 52 IN_PROGRESS: 1 OPEN: 1 ...

Managing input changes in a loop using Vue.js

Can someone verify if the code below is correct, or suggest a better approach? I am trying to handle changes in input values. I have a set of custom options: customOptions: { 1:"test 1", 2:"test 2", 3:"test 3", } These ...

When interacting with a <select> element, the behavior of test script execution varies between Firefox and Chrome

I've encountered an unusual problem that I need help describing and solving. Your assistance is greatly appreciated! The issue I'm facing involves Testcafe behaving differently when running the same test script on various browsers. testcafe: ...

Utilizing a solo attribute within a Vue3 composable

I'm currently using a composable function to load images in my Vue3 project. While I've been able to successfully pass all the props as one object, you can check this question for reference, I'm facing an issue with passing a specific proper ...

Accessing a specific attribute of an object contained within an array

Currently, I am utilizing Vue.js in my project and have implemented a method that involves comparing values from two different arrays. array1: [{ name: 'test1', somevar: true }, { name: 'test2', somevar: false }] array2: ['test1 ...

Communicating Data Between Controllers in Node.js

Within my PlantsController, I extract the Plants using the following method: function getAll() { const plants= HttpRequestPromise.get(config.ApiURL+'allPlants', config.head); return plants; } export class PlantsController { ... public ...

Non-reactive arrays in Vue.js

I am facing an issue. Here is the problem: data: { tracks: [] } The tracks array will contain a complex object. I want to achieve reactivity when assigning a new value to tracks nested object, but I do not need deep reactivity for the object. ...

What is the process for assigning a serial number to each row in the MUI DataGrid?

Initially, the server is accessed to retrieve some data. After that, additional data is added. While the data does not contain an ID, the form must still display a serial number. const columns: GridColDef[] = [ { field: 'id' ...

Prolong and reassign a vuetify component

Is it possible to add custom props to the v-card-title component in Vuetify, while still using to call the component with the custom props? How can this be achieved successfully? You can see an example at codesandbox here: https://codesandbox.io/s/71nr1w ...

Showing a Vue component within a Laravel Blade template

Currently, I am performing a basic calculation within app.js by multiplying the product price with the quantity. My goal is to showcase the total value in Laravel for users to preview their order. app.js const app = new Vue({ el: '#item', ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...

What causes the typescript error in my code: The argument being passed is either a string, an array of FilterData, an array of numbers, or an array of Moments, which is not compatible with a parameter of type 'string'?

When writing my code, I have the need to utilize various types for different scenarios. Depending on the situation, the type may be a string, number[], FilterData[] (a custom type), or Moment[]. To address this requirement, I defined the type as: export ty ...

"Learn how to retrieve and assign a value to a select2 dropdown in Vue.js

Currently, I am utilizing vuejs to create and delete dynamic select elements, which is functioning properly. To view the working example, please click here: https://jsfiddle.net/nikleshraut/fgpdp700/2/ var vm = new Vue({ el: "#app", data: { opt ...

Design interactive images in NativeScript

I need assistance setting up clickable images in NativeScript. My goal is to arrange 5 images horizontally, and when one image is clicked, the images to its left should change their values. Here's what I've attempted: <Label col="0" row="0" ...

Tips for gathering an array of checkboxes within a dynamic array of items using Vue.js and Vuetify

I am currently working on a role permission system where I have defined a resource array containing items that users can access, as well as checks representing the permissions for each resource. My goal is to dynamically assign a role with these resources ...