Joost Kaal
Joost Kaal

Reputation: 483

What is the syntax to using await and async in asynchronous functions using nodejs?

I am trying to create a basic API in nodejs to perform CRUD actions on a database. I do not understand why the result is undefined

exports.getPlaylist = async function (req, res) {
  console.log('Recieved getPlaylist request');
  result = await connection.executeQuery('SELECT * from Users');
  res.status(200).send(result);
  console.log(result); // Logs undefined
};

This is the function that gets called and gets the data from the database:

async executeQuery(query) {
    connection.query(query, function (err, result) {
        if (err) {
            console.log('Error executing query: ' + err);
        }

        console.log(result); // logs correct data
        return result;

    });
}

Upvotes: 0

Views: 311

Answers (2)

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

The execute is not a promise base function, you cannot use await on a callback function.

change the execute function to promise base

Example:

 executeQuery(query) {
  return new Promise( (resolve, reject) => {
    connection.query(query, function (err, result) {
      if (err) {
          console.log('Error executing query: ' + err);
          reject('Error executing query: ' + err);
      }

      console.log(result); // logs correct data
      resolve(result);

  });
  });

}

Add try catch in your calling function

exports.getPlaylist = async function (req, res) {
  console.log('Recieved getPlaylist request');
  try{
    result = await connection.executeQuery('SELECT * from Users');
    res.status(200).send(result);
    console.log(result); // Logs undefined
  } catch(error) {
    console.log(error)
  }

};

Upvotes: 1

Cody Geisler
Cody Geisler

Reputation: 8617

You need to "promisify" your callback. (see require('utils').promisify ) for a shorthand for applying to functions that follow node.js callback style (function(err,result){}).

executeQuery(query) {
    return new Promise((res, rej) => {
        connection.query(query, function (err, result) {
            if (err) {
                console.log('Error executing query: ' + err);
                rej(err)
            } else {
                console.log(result); // logs correct data
                res(result);
            }
        });
    });
}

Now inside an async function you can await executeQuery(query)

Upvotes: 2

Related Questions