【发布时间】:2018-12-26 00:57:24
【问题描述】:
我在 Nuxt.js 中有这个 Axios Async Await 代码,我不确定如何以及将 Promise.all 放在这里。我试图承诺getThemes() 和getData()。有人可以帮我处理Promise.all 代码吗?
我必须将Promise.all 放在mounted() 中吗?
mounted() {
this.getData(this.$route.params.id);
this.getThemes();
},
methods: {
async getThemes() {
this.loading = true;
await axios.get(`${process.env.API_URL}/v1/communication/email-themes`, {}).then((response) => {
this.theme = response.data.data;
this.selected = this.theme.filter(t => this.themeId === t.id)[0].id;
this.loading = false;
}).catch((error) => {
this.loading = false;
this.errormsg = error.response.data.message;
});
},
async getData(id) {
this.loading = true;
await axios
.get(`${process.env.API_URL}/v1/communication/email-templates/${id}`)
.then(({
data
}) => {
this.templateName = data.data.name;
this.templateCode = data.data.content;
this.themeId = data.data.theme_id;
this.loading = false;
}).catch((error) => {
this.loading = false;
this.errormsg = error.response.data.message;
});
},
async patchData(id) {
await axios.put(`${process.env.API_URL}/v1/communication/email-templates/${this.$route.params.id}`, {
name: this.templateName,
content: this.templateCode,
theme_id: this.selected
}).then((response) => {
this.results = response.data;
this.loading = false;
}).catch((error) => {
this.loading = false;
this.errormsg = error.response.data.message;
});
}
}
【问题讨论】:
-
我认为您在这里问的不止一件事,我的回答解决了您实际要问的问题,但也许您应该避免在
getThemes()和getData()上设置this,而只需使用mounted()中的 promise 的返回值。此外,您使用await很差,您不应该使用then或catch,而是使用try catch块。 -
代码中的另一个问题是,如果
getThemes()' andgetData()` 都失败,其中一个将替换另一个errormsg。使用Promise.all后,您可以捕获这两个错误并将它们连接起来。 -
您好,感谢您的回复,您认为我应该替换所有方法吗?我对这个 Asnyc Await 很陌生,上面的代码不是我的,它是由我的同事制作的,我必须修复他的代码。
-
您可以开始使用我的代码及其模拟的异步请求,如您所见,没有
then。为了捕捉错误,你应该实现一个或多个 `try catch' 块。 -
您也可以用您的 axios 调用替换
getPromise():getPromise(1)将变为axios.get(`${process.env.API_URL}/v1/communication/email-themes`, {})。
标签: javascript vue.js promise nuxt.js