Stock Price Checker problem with async/await

Why doesn’t it work that way?

let name = req.query.stock;
(async () => {
    try {
        console.log("before save");
        Stock.exists({ stock: name }, (err, result) => {
            if (!result) {
                let newStock = new Stock({
                    stock: name,
                });
                    await newStock.save();
            }
        });
        console.log("after save");
        console.log("before find");
        Stock.findOne({ stock: name }, (err, document) => {
            if (err) return console.error(err);
            console.log(document);
        });
        console.log("after find");
    } catch (err) {
        console.log(err);
    }
})();

Because you’re trying to use await inside a regular function.

Where do I put the async?
What is the solution?

I assume that it’s mongoose.
If you don’t provide the callback function, then it’ll return promise. So you should remove the callback and put await before each db request.

2021-03-11_18h16_43

You didn’t remove the callback.
It should be something like this:

  const result = await Stock.exists({ stock: name });

  if (!result) {
    let newStock = new Stock({
      stock: name,
    });
    await newStock.save();
  }

Oh thank you! It works well this way.