我正在开发 Nuxt.js 应用程序并尝试使用一种async方法从 api 获取数据,但该async方法的结果始终是undefined。看起来我的方法没有等待响应。我不知道我错过了什么。这是我的代码methods: {..}async getSomething() { console.log("getSomething"); if (condition) { axios .get("api_url") .then((response) => { console.log("getSomething success"); return "success"; }) .catch((error) => { console.log("getSomething fail 1"); return "fail"; }); } else { console.log("getSomething fail 2"); return "fail"; }}doSomething() { console.log("do Something"); this.getSomething().then((result) => { console.log("result", result); if (result === "success") { // do something on success } else { // do something on fail } }); console.log("end doSomething");}我已经尝试记录this.getSomething(),结果是Promise {<pending>}在这里,当一个方法被调用时created () {..}this.doSomething()// doSomething// getSomething// end doSomething// getSomething success// result undefined
1 回答
慕哥6287543
TA贡献1831条经验 获得超10个赞
我认为您的部分问题是您将编写代码的异步/等待风格与承诺链风格混合在一起。当您返回“失败”或“成功”时,您通常是从axios.get回调中返回,而不是从getSomething方法中返回。您可能想像这样重写代码:
async getSomething () {
console.log('getSomething')
if (condition) {
try {
let response = await axios.get('api_url')
console.log('getSomething success')
return 'success'
}
catch(error) {
console.log('getSomething fail 1')
return 'fail'
}
} else {
console.log('getSomething fail 2')
return 'fail'
}
}
添加回答
举报
0/150
提交
取消