Mike Vlad
Mike Vlad

Reputation: 371

Node mysql pool.query await for result

I'm using node mysql package. I don't have much experience in JS and i'm trying to turn this function into an async function so i can wait for the result:

function execute_q (q) {
  var results = _this.pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    if (error) throw error;
    console.log(results[0].solution)
  })
}

I've tried like this:

async function execute_async (q) {
  return await new Promise(function(resolve,reject){
    _this.pool.query(
      q,
      function (error, results, fields) {
        if (error) {
          reject(error);
        } else {
          resolve(results)
        }
      })
  })
}

but when i run var results = await execute_async(q) i keep getting await is only valid in async function. What am i doing wrong?

Upvotes: 0

Views: 7047

Answers (4)

Jeff Quinones-Finch
Jeff Quinones-Finch

Reputation: 21

On the line "var results = await _this.pool..." an error is thrown "await has no effect on this type of expression", and the code just hangs.

Upvotes: 2

bhuvnesh pattnaik
bhuvnesh pattnaik

Reputation: 1463

I guess this will work, this is what you want...

async function execute_q (q) {
    try {
        var results = await _this.pool.query('SELECT 1 + 1 AS solution');
        console.log(results[0].solution);
        return results;
    }
    catch(err) {
        throw err;
    }
}

Upvotes: 1

ALOK VERMA
ALOK VERMA

Reputation: 97

you can try this

async function execute_async (q) {

  try {
    var results = await _this.pool.query('SELECT 1 + 1 AS solution');
    return results;
  }
  catch (err) {
    throw err
  }
}

Upvotes: 2

Neel Debnath
Neel Debnath

Reputation: 195

Add an async before the function in which you have placed the execute_async(q) function and check the result.

Upvotes: 1

Related Questions