3 回答

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
你不需要自己解開承諾.then,因?yàn)槟阋呀?jīng)在一個(gè)異步函數(shù)中。當(dāng)您使用.then((result) => {...})該箭頭功能時(shí)不再是異步的。我的建議:
try {
const result = await this.$validator.validateAll()
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
} catch (error) {
this.state = 'ERROR';
this.response.push(error);
}
或者,您可以通過(guò)執(zhí)行以下操作將箭頭函數(shù)標(biāo)記為異步:
this.$validator.validateAll().then(async (result) => {

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
我們知道這async..await是對(duì)關(guān)鍵字,
只是您async在上層函數(shù)中使用過(guò)。您的內(nèi)部函數(shù)沒有 async 關(guān)鍵字,但您await在函數(shù)內(nèi)部使用過(guò)。這就是為什么它顯示錯(cuò)誤。只是我標(biāo)記了不是的功能async
(result)/*this function has not async*/ => {
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
});
所以你必須在內(nèi)部函數(shù)中使用 async 關(guān)鍵字。
async (result) => { /* 你的代碼在這里 */ }

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
登錄函數(shù)已經(jīng)是異步函數(shù),你可以用 await 調(diào)用 this.$validator 而不是 .then()。因?yàn)閮?nèi)部 .then(() => {}) 是另一個(gè)回調(diào)函數(shù)而不是異步函數(shù)。這是我的建議:
try {
let result = await this.$validator.validateAll();
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
} catch (error) {
this.state = 'ERROR';
this.response.push(error);
}```
添加回答
舉報(bào)