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"
]
}