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

290
Views
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 answers
Answer question

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 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!