Correct Async/Await usage with Axios

Issue

I’m working with axios to post user responses to a database. I’m using this set up shown below to handle many posts back to back. I’m wanting to make sure that this is the correct set up to avoid backing up requests.

Is this the correct way to use async and await when using Axios?

// Frontend React Code
// Posting conclusionInput to Mongodb
const postConclusion = async () => {
  await axios({
    method: "POST",
    data: {
      conclusion: conclusionInput,
    },
    withCredentials: true,
    url: "http://localhost:4000/conclusion",
  }).then((res) => console.log(res));
};

//Backend Node / Express code
app.post("/conclusion", (req, res) => {
  console.log("Attempting to post the conclusion");
  User.findOne({ username: req.user.username }, async (err, user) => {
    if (err) throw err;
    if (user) {
      (user.conclusion = req.body.conclusion), await user.save();
      res.send();
    }
  });
});

Solution

Frontend

In an async function use await and try/catch. Any .then calls can be rolled out into const x = await y variables.

Return values from promise functions, in case you want to use them.

const postConclusion = async () => {
  const res = await axios({
    method: "POST",
    data: {
      conclusion: conclusionInput,
    },
    withCredentials: true,
    url: "http://localhost:4000/conclusion",
  })
  console.log(res)
  return res
};

Backend

Again, if you are going with async use that API consistently.

Mongoose provides a promise API, so use that too.

app.post("/conclusion", async (req, res) => {
  try {
    console.log("Attempting to post the conclusion");
    const user = await User.findOne({ username: req.user.username })
    if (!user) {
      return res.send('not found')
    }
    user.conclusion = req.body.conclusion
    await user.save()
    return res.send('saved')
  }
  catch (error) {
    console.error(error)
    return res.send('error')
  }
});

Answered By – Matt

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published