0

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;

    });
}
1
  • executeQuery does not return anything Commented Jan 20, 2020 at 14:36

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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)
  }

};

1 Comment

You don't need to add async to executeQuery function. You're already returning a Promise. async just wrap the function into a Promise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.