H
H
hollanditkzn2018-01-11 17:26:34
MySQL
hollanditkzn, 2018-01-11 17:26:34

How do I make an array of received values ​​from mysql?

Made a request to the database

let user = ctx.state.user[0];
        let sql = 'SELECT id_theme FROM access WHERE id_user = ?';
        let themes = db.query(sql, [user.id], async (err, result) => {
            if(err) console.error(err);
            console.log(result);
            await result;
        });

At my output I get the following data
[ RowDataPacket { id_theme: 1 },
  RowDataPacket { id_theme: 2 },
  RowDataPacket { id_theme: 3 },
  RowDataPacket { id_theme: 2 },
  RowDataPacket { id_theme: 3 } ]

Only in pug I can't drive him
each theme in themes
                     p=theme

Because it's an object, how do I make it an array?
Cannot convert object to primitive value

Tried more
So
await JSON.stringify(result);
but it didn't help either.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Abcdefgk, 2018-01-11
@hollanditkzn

If you definitely want to write the words async and await, and you definitely want to get the result of the query into the themes variable, then you need to write something like this:

asyncFoo();
async function asyncFoo() {
  var themes = await new Promise( resolve => {
    var sql = 'SELECT id_theme FROM access WHERE id_user = ?';
    db.query(sql, [user.id], (err, result) => {
      if(err) console.error(err);
      resolve(result);
    });
  }).then( result => {
    return result;
  };
  console.log(themes);
  // тут его в pug и передавать
}

Is it worth it to bother so much for the sake of trendy async/await? - Well, someone likes it.

R
RidgeA, 2018-01-11
@RidgeA

Well, actually, an array is returned in the callback
And I don’t know how pug works with it.
There is a suspicion that this problem is due to incorrect work with async / await - why is it even there?

let themes = db.query(sql, [user.id], async (err, result) => {
            if(err) console.error(err);
            console.log(result);
            await result;
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question