Victor Thadeu
Victor Thadeu

Reputation: 107

How can I force my function to wait promises before moving on?

I read another posts but they were not solving my particular problem.

I'm trying to move all dependent entries from one user to a default one before deleting the user. But even with Promise.all().then() I'm getting an error saying that I still have foreign key constraints preventing me to delete the user (But if i try to delete it manually after that it works fine, because I really moved all the dependencies to the default user).

async delete (req, res){
try {
  const {id} = req.body;

  // Here I call all the recipes that this user owns
  const recipes = await Recipe.find({where: {chef_id: id}});

  // Create the Promises for every UPDATE request in the Database
  const changeChefPromises = recipes.map( recipe => {
    Recipe.update(recipe.id,{chef_id : 1})
  });

  /* HERE is the problem, I'm trying to update every single recipe
     before I delete the User, but my program is trying to delete
     the User before finishing the Update process for all dependencies */ 

  await Promise.all(changeChefPromises).then(() => {
    Chef.delete(id);
  });


  return res.redirect(`/admin/chefs`);

} catch (err) {
  console.error(err);
}

}

Upvotes: 1

Views: 191

Answers (1)

Khalos
Khalos

Reputation: 2373

const changeChefPromises = recipes.map( recipe => {
    Recipe.update(recipe.id,{chef_id : 1})
});

This is not creating an array of promises which is what you're expecting. You either need to remove the body of the arrow function or explicitly return the promise inside the body.

E.g.

const changeChefPromises = recipes.map(recipe => Recipe.update(recipe.id,{chef_id : 1}));

or

const changeChefPromises = recipes.map( recipe => {
    return Recipe.update(recipe.id,{chef_id : 1})
});

Also, it's a bit weird to mix async/await and .then() so it might also be a good idea to change:

  await Promise.all(changeChefPromises).then(() => {
    Chef.delete(id);
  });

to

await Promise.all(changeChefPromises);
await Chef.delete(id);

Upvotes: 2

Related Questions