我正在尝试创建一个与API通讯的服务,我对async / await不太熟悉,但是我面临以下问题,根据我在文档中阅读的内容,这没有多大意义。 / p>
如果我尝试使用await从异步函数(UserAuthService.login)中获取结果,则会给我一个错误消息: “'await'表达式仅在异步函数中允许”
当我尝试获取结果时,组件Login中发生错误,如果login函数是异步函数,则“ login”函数可以正常工作,为什么我会收到此错误?如何从异步函数中获取结果?
auth_user_service.ts:
const UserAuthService = {
/**
* Login the user and store 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",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
答案 0 :(得分:2)
由于在方法内部使用了await
,因此必须将其声明为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)
}
}
还要注意,由于使用了async
关键字,该方法现在返回一个Promise
。由于您使用的是TypeScript,因此还必须将其返回类型从void
更改为Promise<void>
。