How to write this properly with async/await

Multi tool use
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.
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
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.