Axios子请求顺序错误



我试图用Wordpress API进行搜索,我没有请求的问题,但在我的功能期间,我的结果不再从第一个请求订购。我解释一下。我的第一个axios请求是搜索,它返回带有标题和id的帖子列表。但是在foreach中,我想创建一个子请求来获取id:

的post
methods: {
getSearch: async function () {
const query = "/search?subtype=post&search=" + this.$route.query.q;
const response = await this.axios.get(query);
return response.data;
},
getPost: async function (id) {
const query = "/posts/" + id;
const response = await this.axios.get(query);
return response.data;
},
getCategorie: async function (id) {
const query = "/categories?post=" + id;
const response = await this.axios.get(query);
return response.data;
},
search: async function () {
await this.getSearch().then((search) =>
Promise.all(search).then(
search.forEach(async (tuto) => {
console.log(tuto.title); // Result in order
await this.getPost(tuto.id).then((post) => {
console.log(post.title); // Not the same order
});
})
)
);
console.log(this.tutos_search);
},
},

我很确定这是async/await的问题,但我找不到解决方案。

这是控制台:

487
493
480
463
458
Proxy {}[[Handler]]: Object[[Target]]: Array(0)[[IsRevoked]]: false
480
487
458
493
463

可以看到,第一个日志和第二个日志的顺序不一样,在中间我们看到最后一个console.log。我不明白为什么,因为我有等待。

仅供参考,我使用VueJS。谢谢你。

谢谢大家,我不是100%满意,但我的代码下面工作!!


methods: {
getSearch: async function () {
const query = "/search?subtype=post&search=" + this.$route.query.q;
const response = await this.axios.get(query);
return response.data;
},
getPost: async function (id) {
const query = "/posts/" + id;
const response = await this.axios.get(query);
return response.data;
},
getCategorie: async function (id) {
const query = "/categories?post=" + id;
const response = await this.axios.get(query);
return response.data;
},
search: async function () {
const search = await this.getSearch();
for (let i = 0; i < search.length; i++) {
const id = search[i].id;
const post = await this.getPost(id);
const categories = await this.getCategorie(id);
post.categories.length = 0;
post.categories = categories;
console.log(post);
}
},
},

相关内容

  • 没有找到相关文章

最新更新