简体   繁体   English

为什么我的 javascript 会忽略第二次等待?

[英]why does my javascript ignores the second await?

blogCategorie and blog are both CRUD-objects. blogCategorie 和 blog 都是 CRUD 对象。 blogCatergorie.getAll gives me all the category objects. blogCatergorie.getAll给了我所有的类别对象。 I loop through each category and push the name of the category in to an array (categorieTitles).我遍历每个类别并将类别的名称推入一个数组(categorieTitles)。 So far so good.到目前为止,一切都很好。 In the map function i want to retrieve all the blogs from that category with blog.getBlogsFromCategory , but it looks like the compiler ignores the await in front of this promise.在 map function 中,我想使用blog.getBlogsFromCategory从该类别中检索所有博客,但看起来编译器忽略了此 ZB321DE3BDC299EC807E9F795D 前面的等待。 It pushes the blogs at the end of the code when i already did the `console.log('Blog containers').当我已经执行了`console.log('Blog containers') 时,它会在代码末尾推送博客。 Did i do something wrong?我做错什么了吗?

Code代码

let categorieTitles = [];
let blogContainers = [];

await blogCategorie.getAll().then((allCategories) => {
   console.log('after 1st await');
   allCategories.map(async (categorie) => {
      categorieTitles.push(categorie.name);
      await blog.getBlogsFromCategory(categorie.id).then((blogs) => {
         console.log("after 2nd await");
         let blogGroup = [];
         blogs.map((blog) => {
            blogGroup.push(blog);
         });
         blogContainers.push(blogGroup);
      });
   });
});

console.log('Categorie titels', categorieTitles);
console.log('Blog containers', blogContainers);

output output

after 1st wait
Categorie titels [ 'Kinderen en psychologie', 'Efficiënt lesgeven' ]
Blog container []
after 2nd await
after 2nd await

async-await inside a map do not work. map 中的async-await不起作用。

Also, if you are using await, then ideally you should not use the .then syntax, since you can store the response of your asynchronous operation in a variable.此外,如果您正在使用 await,那么理想情况下您不应该使用.then语法,因为您可以将异步操作的响应存储在变量中。

You can change the map to a for-in loop as below:您可以将map更改为for-in循环,如下所示:


const allCategories = await blogCategorie.getAll();
console.log('after 1st await');
for (const categories of allCategories) {
   categorieTitles.push(categorie.name);
   const blogs = await blog.getBlogsFromCategory(categorie.id);
   console.log("after 2nd await");
   let blogGroup = [];
   blogs.map((blog) => {
     blogGroup.push(blog);
   });
   blogContainers.push(blogGroup);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM