简体   繁体   中英

How do we use Async, and what is the best way in nodeJS

I'm trying to pass a query to my database, then send the result to my client side, but it looks like the request is async, because my request happens after that my post request returns the value.

How do I set an await for request?

My database connection

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'my_password',
    database: 'MEETME'
});

connection.connect(function(err) {
    if (err) {
        console.log("error while connecting to database");
        console.log(err.code);
    }
});

// function that query database <-------

function queryDatabase(userQuery) {
    connection.query(userQuery, function(err, result) {
        if (err) {
            throw err;
        }
        console.log("before");
        return result;
    });
}

and this is my post request

//POST
app.post('/signin', function(request, response) {
    var query = queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3");
    console.log(query);
    console.log("after");
    response.end(query, 200);
});

the result in the console is:

undefined
after
before

Change the implementation of queryDatabase function to return a promise. Any function that returns a promise can be awaited.

function queryDatabase(userQuery){
     return new Promise((resolve,reject) => {
        connection.query(userQuery, function(err, result){
            if(err){
              reject(err);
            }
            console.log("before");
            resolve(result);
        }); 
     }); 
}



app.post('/signin', async function(request, response){
    var query = await queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3");
    console.log(query);
    console.log("after");
    response.end(query, 200);
});

Welcome to Node.js where everything is intended to be asynchronous and unless you explicitly structure your code in a way that cascades one event to another there's no obligation on the part of the code to run in any particular order at all.

I'd strongly recommend picking up on Promises as a way of organizing code if you're not familiar with this concept. This wraps up a lot of tricky programming into some neat, tidy methods, and makes chaining, fan-out and fan-in actually pretty simple.

For example, rewritten with Sequelize , a database layer that uses promises:

function queryDatabase(userQuery){
   console.log("before");

   return connection.query(userQuery);
}

You return the promise, and that's used to chain. If you don't you must accept a callback argument and chain that through. Return values are largely ignored:

function queryDatabase(userQuery, cb){
   connection.query(userQuery, function(err, result){
      cb(err, result);
   });
   console.log("before");
}

You can see there's a lot more cruft already, and even more if you needed to build off of that. Inserting optional steps in callback driven code is tricky .

Promises make your code end up looking like this:

app.post('/signin', function(request, response){
  queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3")
    .then(function(results) {
      console.log(results);
      console.log("after");
      response.end(query, 200);
    });
});

It's also trivial to patch in error handling in one place with catch to handle errors.

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