Home > Software design >  confusion about using .then .catch
confusion about using .then .catch

Time:09-05

Am i supposed to use .then and .catch if I am using async/await??? Is the exception handled by async/await or in some cases we have to use .then and .catch

Before using Async/Await


message.save()
        .then(() => {
            console.log("Saved");
            return Message.findOne({ message: "badword" })
        })
        .then(censored => {
            if (censored) {
                console.log("Censored owrd Found", censored);
                return Message.deleteOne({ _id: censored.id })
            }
            io.emit("message", req.body);
            res.sendStatus(200);
        })
        .catch((err) => {
            res.sendStatus(500);
            return console.error(err);
        })

After using Async/Await



    await message.save();

    console.log("saved");

    var censored = await Message.findOne({ message: "badword" })

    if (censored)
        await Message.deleteOne({ _id: censored.id })
    else
        io.emit("message", req.body)

    res.sendStatus(200);```

CodePudding user response:

Work with try/catch in case you can use async/await. Like this:

try {
  await message.save();
  console.log("saved");

  var censored = await Message.findOne({ message: "badword" })

  if (censored)
      await Message.deleteOne({ _id: censored.id })
  else
      io.emit("message", req.body)

  res.sendStatus(200);
} catch (err) {
  res.sendStatus(500);
  console.error(err);
}

CodePudding user response:

It is not correct because await only waits to the referenced function as await function(). For this reason, the code below the first await will run before the previous function has finished.

You could await using Promise.all() when you want run simultaneous tasks.

But as I can see, you need to wait until censored has value, so , in this cases, I use then(), catch().

  • Related