简体   繁体   English

如何使用异步/等待正确编写

[英]How to write this properly with async/await

Newbie web developer here, I am making a project and was suffering a bit of callback hell, so I read a abit and found out about async/await, I tried to use it in my code (in a seed file for my db to try my website but it doesnt seem to be working. Basically I have categories, sub-categories and prodjucts and I want to create all categories first, then sub-categories and then the products but I can't seem to get it to work in order. 新手Web开发人员在这里,我正在做一个项目,并且遭受了一些回调的麻烦,所以我读了一点,发现了关于异步/等待的知识,我试图在代码中使用它(在我的数据库尝试使用的种子文件中)我的网站,但似乎无法正常工作,基本上我有类别,子类别和产品,我想先创建所有类别,然后再创建子类别,然后创建产品,但我似乎无法使其按顺序工作。

Here is my code: 这是我的代码:

async function addCats() {
  //CREATE CATEGORIES
  //async.each(categories, function(category, callback){
  for (const category of categories) {
    await Category.create({
      name: category
    }, function(err, createdCategory) {
      if (err)
        console.log(err);
      else {
        console.log("Created category ");
      }
    });
  }
}

async function addSubs() {
  sub_categories.forEach(function(sub) {
    //Find the Parents ID
    Category.find({
      name: sub.parent
    }, function(err, foundParent) {
      if (err)
        console.log(err);
      else {
        SubCategory.create({
          name: sub.name,
          parent: {
            name: sub.parent,
            id: foundParent._id
          }
        }, function(err, createdSub) {
          if (err)
            console.log(err);
          else
            console.log("Created sub-category");
        })
      }
    })
  })
}

function seedDB() {
  Category.remove({}, function(err) {
    if (err)
      console.log(err);
    else {
      SubCategory.remove({}, function(err) {
        if (err)
          console.log(err);
        else {
          Product.remove({}, function(err) {
            if (err)
              console.log(err);
            else {
              addCats();
              addSubs();

              //CREATE PRODUCTS
              products.forEach(function(product) {
                //Find category ID
                Category.find({
                  name: product.category
                }, function(err, foundCategory) {
                  if (err)
                    console.log(err);
                  else {
                    //Find sub-category ID
                    SubCategory.find({
                      name: product.sub_category
                    }, function(err, foundSubCategory) {
                      if (err)
                        console.log(err);
                      else {
                        //See if the ID's are linked?
                        console.log('fsub: ' + foundSubCategory + ' fsubP: ' + foundSubCategory)
                        if (!foundSubCategory.parent._id.equals(foundCategory._id))
                          console.log("This is not a valid categories sub-category");
                        else {
                          //CREATE PRODUCT
                          Product.create({
                            name: product.name,
                            category: product.category,
                            subcategory: product.sub_category,
                            price: product.price,
                            description: product.description
                          }, function(err, createdProduct) {
                            if (err)
                              console.log(err);
                            else
                              console.log("Created product: " + createdProduct);
                          })
                        }
                      }
                    })
                  }
                })
              })
            }
          });
        }
      });
    }
  });
}

Even if I comment out the last part where I add the products I still cant get the categories to be created first and then the sub-categories, they continue to get created out of order. 即使我注释掉添加产品的最后一部分,我仍然无法先创建要创建的类别,然后才创建子类别,但它们仍然会无序创建。

Thanks 谢谢

So, a something that jumped out at me. 所以,某种东西突然出现在我身上。

Async/await work on Promises, so you need to make sure you're using the Promise syntax of your ORM/ODM library. 异步/等待在Promises上工作,因此您需要确保使用的是ORM / ODM库的Promise语法。 Assuming you're using Mongoose (or something like it), passing a callback to the .create() calls (for example) will push it into using the callback style, and not return a Promise that async/await can hook into. 假设您使用的是Mongoose(或类似的东西), .create()回调传递给.create()调用(例如) 会将其推入使用回调样式,而不返回async / await可以挂接到的Promise。

As an example, your first function should look like this instead: 例如,您的第一个函数应如下所示:

async function addCats() {
  for (const category of categories) {
    try {
       await Category.create({
         name: category
       });
       console.log('created category');
    } catch (e) {
       console.log(e.message);
    }
  }
}

Also note you're not returning anything; 还要注意,您什么也不返回; not sure if that's intentional or not. 不知道这是否是故意的。

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

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