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

294
Visualizações
Express: MySQL query doesn't push code to a list

I have been trying to push the results of MySQL query to a list(shoppingList), but the shoppingList is always empty, even though I'm getting 2 results back.

I think the problem is somewhere with handling the promise, but I haven't been able to figure it out:

static async showShoppingList(userId) {
    let shoppingList = [];
    const sql =
      "SELECT item_name, family_member_name FROM shopping_list WHERE user_id = (?)";
    await db.promise().query(sql, [userId], function (err, results) {
      for (const result of results) {
        shoppingList.push(result)
        console.log(shoppingList) // Here it appears with results
      }
    });
    console.log(shoppingList) // Here it appears empty
    return shoppingList;
  }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

That's because the callback function(err, results) is executed asynchronously, after the database has returned the results, whereas the other statement is executed synchronously:

  1. db.promise().query sends the query to the database.
  2. The empty shoppingList is written to the console and returned.
  3. After the database has returned the results, the callback function is executed, writing the full shoppingList to the console.
about 4 years ago · Juan Pablo Isaza 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