gpt4 book ai didi

javascript - 如何使用 Promise.all 使用 Axios Async Await

转载 作者:行者123 更新时间:2023-12-03 22:55:29 24 4
gpt4 key购买 nike

我在 Nuxt.js 中有这个 Axios Async Await 代码,我不确定如何以及在哪里放置 Promise.all这里。我试图 promise getThemes()getData() .有人可以帮我处理 Promise.all代码?

我必须把 Promise.allmounted() ?

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;
});
}
}

最佳答案

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.



引用 - Async function

所以你可以这样做
{
mounted() {
this.loading = true;
Promise.all([this.getThemes(), this.getData(this.$route.params.id)])
.then(values => {
//first return value
this.theme = values[0];
this.selected = this.theme.filter(t => this.themeId === t.id)[0].id;
//second return value
this.templateName = values[1].name;
this.templateCode = values[1].content;
this.themeId = values[1].theme_id;

this.loading = false;
})
.catch(error => {
this.errormsg = error.response.data.message;
this.loading = false;
});
},
methods: {
async getThemes() {
const response = await axios.get(
`${process.env.API_URL}/v1/communication/email-themes`,
{}
);
return response.data.data;
},
async getData(id) {
const response = await axios.get(
`${process.env.API_URL}/v1/communication/email-templates/${id}`
);

return response.data.data;
}
}
};

然后使用 Promise.all 将数组中的两个异步函数作为参数传递。

关于javascript - 如何使用 Promise.all 使用 Axios Async Await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51396360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com