简体   繁体   中英

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;

    });
}

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)

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

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM