Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS MySQL waiting for query results

I want to make a function that query data to MySQL, and wait for the result.

const results = await message.client.db.query("SELECT * FROM TABLE WHERE condition");
console.log(results);   

My issue is that results doesn't contain the raw data as I would expect it, but a query object :

<ref *1> Query {
  _events: [Object: null prototype] {
    error: [Function (anonymous)],
    packet: [Function (anonymous)],
    timeout: [Function (anonymous)],
    end: [Function (anonymous)]
  },
  _eventsCount: 4,
  _maxListeners: undefined,
  _callback: [Function (anonymous)],
...
    _connectCalled: true,
    state: 'authenticated',
    threadId: 27,
    [Symbol(kCapture)]: false
  },
  [Symbol(kCapture)]: false
}

I have been looking for a doc on that Object, and I couldn't find it. I suppose it is a sort of Promise, as the Query object is returned before the results are received :

console.log("1 - Before Query");
const results = await message.client.db.query("SELECT * FROM TABLE WHERE condition", async function (err, result, fields) {
    if (err) throw err;
    console.log("2 - Query result : ");
    console.log(result);
});
console.log("3 - After Query");
console.log(results);   

OUTPUT : 
1 - Before Query
3 - After Query
<The Query Object>
2 - Query result : 
<An array with my data>

I have seen a lot of example where people use await connection.query("...") to wait for the results, and I don't understand where does this Query object comes from.

I know I can wait for the result with something like that :

    message.client.db.query("SELECT * FROM TABLE WHERE condition", async function (err, result, fields) {
        if (err) throw err;
        do_something(result);
    });

But I first find it really heavy, and hard to use when you do a lot of requests. Also I need an async function that return a value from database, and since await connection.query("...") can't wait for the result, I don't know how to do it.

like image 873
Mister Aqua Avatar asked Nov 20 '25 07:11

Mister Aqua


1 Answers

If you are using mysql2 package to connect to the database you can do something like this:

await con1.promise().query("your query here")
    .then( ([rows,fields]) => {
        your var = rows[0]['field1'];
        return nome_completo;
    })
    .catch(console.log)

Where con1 is the connection you defined. With promise() you are promisifying your query so you can use await