Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Converting Express app from promises to async/await

I've been using Promises for a long time and I've always disliked how bulky written code looked. So it makes sense that I love async/await (in theory).

However, you can only use await within an async function. If I currently have each route as a function (ex export function createLike(req, res, next)), can that route be an async function? Is there anything I need to check if I do that? Or do strange things happen if I do that? I could keep the function as a normal function with an async function called within it like so (if that's the case):

export function createLike(req, res, next) {
    doStuff()  // does this need to be "await doStuff()" if it's the only actionable call in the parent function?

    async function doStuff() {
        // do asynchronous stuff via async/await
        res.status(200).send('success')
    }
}
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

export async function createLike(req, res, next) {

Easy-peasy. Declaring a function as async does little more than make it return a Promise.

Unravelling your whole trivial example:

export async function createLike(req, res, next) {
  // Don't bother putting inside a 'doStuff' if it's all you have.
  // Get straight to the asyncing
  const { something } = await someAsyncMethod();
  const { foo } = await fetch(`/get/this/${something}`).then((r) => r.json());
  console.log(foo);
  res.status(200).send('success')
}

This will wait until it gets someAsyncMethod()s response, then fetches something, before sending the response.

about 4 years ago · Santiago Trujillo Report

0

Use koa 2+. Its built for async/await stuff.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!