Richlewis
Richlewis

Reputation: 15374

Async/Await post request - nodejs

Before carrying on with the rest of my POST request I need to make a database call and wait for the response of that (in this case wait for the promise to be fulfilled).

app.post("/charge", (req, res) => {
  var user_stripe_id = await queries.get_stripe_id_by_email(req.body.token.email);
}

However I can't await the query as I'm not in an async function. How can I make app.post async ?

In other routes I have done this

app.get('/', async function (req, res) {
  const leagues = await distinctLeagues();
  res.render('home', { leagues: leagues });
});

But I would like to know how to do it with the arrow function syntax.

Upvotes: 0

Views: 3196

Answers (1)

Arjun Komath
Arjun Komath

Reputation: 2852

You can create an async function in es6 as shown below:

app.post("/charge", async (req, res) => {
  var user_stripe_id = await queries.get_stripe_id_by_email(req.body.token.email);
}

Here is an ideal usage for async-await, use it inside a try-catch. Value that is resolved by the promise would be assigned to quote and if the promise is rejected the catch block will be executed.

async function main() {
  try {
    var quote = await getQuote();
    console.log(quote);
  } catch (error) {
    console.error(error);
  }
}

Upvotes: 3

Related Questions