Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

293
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda