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

356
Visualizações
Node and async: Why is await not being honored in a sub-function?

I'm a Node.js student, and I'm writing a brief example. The get on /org works as expected.

With the get on /orgg I tried to segregate the server "fetch the data" logic from the controller. However, the getRowsAsync() immediately returns a Promise.

This "put the await in express.get()" isn't good for hiding logic. If my biz logic needed some sequential Promises then the biz logic would have to bubble into the controller.

How can I do the equivalent to calling "doBizLogic()" in the controller, hiding my awaits, and having the controller wait for the logic to complete? Must I pass a callback function to the biz logic to make this scheme work?

Here is my index.js. I omit database.js, but I borrowed it from https://mhagemann.medium.com/create-a-mysql-database-middleware-with-node-js-8-and-async-await-6984a09d49f4

const express = require("express");
const urlPort = 3000;
let app = express();
let mysql = require("mysql2");
let pool = require("./database");

app.listen(urlPort, () => {
  console.log("Server is running at port " + urlPort);
});

app.get("/", (req, res) => {
  res.send("This app responds to /org and /org/:id only.");
});

app.get("/org", async (req, res) => {
  let rows = await getRows("select * from org");
  // the log always prints a JSON array.
  console.log("in app.get for /org, rows: ", rows);
  res.send(rows);
});

app.get("/orgg", (req, res) => {
  let rows = getRowsAsync();
  // the log() prints immediately prints a Promise.
  console.log("in app.get for /orgg, rows: ", rows);
  res.send(rows);
});

function getRows(sql, params = []) {
  let rows = pool.query(sql, params);
  // the log() prints a Promise.
  console.log("in getRows, rows: ", rows); // returns 
  return rows;
}

async function getRowsAsync() {
  let rows = await getRows("select * from org");
  // the log() prints a JSON array, once it is finally called.
  console.log("in getRowsAsync, rows: ", rows);
  return rows;
}

over 4 years ago · Santiago Trujillo
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