Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda