How to deal with race conditions in nodejs
try this, you can't do async call like this with map. There are patterns to solve this issue. Promise.all is one of them.
const allCardsArray = [...Array(req.body.numOfCards).keys()]await Promise.all( allCardsArray.map((i)=>{ const eachCard = new eachCardModel({ eachCardTitle: String(i) }) return eachCard.save() .then( () => CardDeckModel.findOneAndUpdate({_id: req.cardDeckCreated._id}, {$push:{allCards: doc}}) .then(() => console.log("success")) .catch((error) => console.log(error) || res.status(400).json({ errMsg: "Something went wrong" });) ).catch(() => res.status(400).json({ errMsg: "Something went wrong" })) })) console.log("COMPLETED") //DOES NOT EXECUTE LAST! //THIS RETURNS BEFORE THE .map() is done res.status(200).json({ createdCardDeckID: req.cardDeckCreated._id })})
you can use for of
with async/await
instead of map
like this
const allCardsArray = [...Array(req.body.numOfCards).keys()];for (let i of allCardsArray) { const eachCard = new eachCardModel({ eachCardTitle: String(i), }); try { let doc = await eachCard.save(); await CardDeckModel.findOneAndUpdate( { _id: req.cardDeckCreated._id }, { $push: { allCards: doc } } ); } catch (error) { return res.status(400).json({ errMsg: "Something went wrong" }); }}console.log("success");res.status(200).json({ createdCardDeckID: req.cardDeckCreated._id,});