H
H
hello_itsme2015-12-31 10:21:40
Node.js
hello_itsme, 2015-12-31 10:21:40

How to pass data from mysql query to node.js function?

There is such a function:

var mysql = require('mysql');
db = mysql.createConnection({
  host     : '...',
  user     : '...',
  password : '...',
  database : '...'
});
useItem = function(socket, item_id, amount){
  if(amount >= 1){
    db.query('SELECT ...', function(err, rows) {
      if(rows.length > 0){
        if(rows[0].amount >= amount){
          if((rows[0].amount-amount) >= 1){
            db.query('UPDATE ...');
          }else{
            db.query('DELETE ...');
          }
          return true;
        }else{
          socket.emit('alert', { message: "..." });
          return false;
        }
      }else{
        socket.emit('alert', { message: "..." });
        return false;
      }
    });
  }else{
    socket.emit('alert', { message: "..." });
    return false;
  }
}

The function is designed to write off an item from the user's inventory and will be used in other functions, so it must return true\false to perform further actions. The problem is that accessing the database is asynchronous (db.query...) and return from there does not work quite the way it should. How can the problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Leonovich, 2015-01-02
@hello_itsme

It is necessary that the useItem function return a promise object, external code will work with it. In the body of the function, after the request has been processed, you can resolve or reject this promise with the necessary parameters.
Try to use, for example, this one - https://www.npmjs.com/package/promise.
habrahabr.ru/post/209662

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question