I
I
Ivan Ivanovich2020-06-30 11:02:16
JavaScript
Ivan Ivanovich, 2020-06-30 11:02:16

I don't understand the error in async await?

Hello.
I installed the mysql package to work with the database, but since it is not based on promises, I decided to do the following.

const getDataDB = async q=>{
  return await connection.query(q, (err,result)=>{
    if(err) throw err;
    console.log(1);

    return result;
  });
};


const getData = async ()=>{
  const data = await getDataDB('SELECT * FROM users');
  console.log(2);
  console.log(data);
};

getData();


And the problem is that console log with number 1 appears after console log 2, i.e. getDataDB returns data later than getData receives it.

I don't understand what is output in the console.

<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)],
  _callSite: Error


Please tell me what I did wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-06-30
@IwanQ

since it is not on promises, it will work immediately after calling query. await is waiting for a promise but it's not there. Read more about how async/await works. you need to convert this to promises either via utils.promisify orreturn await connection.query

const getDataDB = q=>{
  return new Promise(( resolve, reject) => connection.query(q, (err,result)=>{
    if(err) reject(err);
    console.log(1);

    resolve(result);
  }));
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question