tux-world tux-world - 3 months ago 6
Node.js Question

Nodejs combine two result of my sql commands

I have two mySql command as get result from database, i'm trying to get them with below codes but it doesn't work correctly

for example:

get results from

userEwallets
table:

function getMoneySenderUserInfo(data, callback) {
var sourceEwalletNumber = data.transferToEwallet.substring(0, 5) + data.registeredMobileNumber.substring(1, data.registeredMobileNumber.length);
var query = "SELECT userEwallets.id as ewalletId, users.id as userId , money_repositories.money as money FROM userEwallets " +
"JOIN users ON users.id = userEwallets.userId " +
"JOIN money_repositories ON userEwallets.id = money_repositories.ewalletId " +
"WHERE ewalletNumber = '" + sourceEwalletNumber + "' ";
connection.query(query, function (err, results) {
if (err) return callback(false);

if (results.length === 0) return callback(false);

callback(true, results[0]);
});
}


get result from
userEwallets
table again to get other result:

function getDestinationTakeMoneyUserInfo(data, callback) {
var query = "SELECT users.id as userId FROM userEwallets " +
"JOIN users ON users.id = userEwallets.userId " +
"WHERE ewalletNumber = '" + data.transferToEwallet + "' ";
connection.query(query, function (err, results) {
if (err) return callback(false);

if (results.length === 0) return callback(false);

callback(true, results[0]);
});
}


now i want to combine this results with this code:

usersInformation = {};
getMoneySenderUserInfo(data, function (success, result) {
if (success) {
usersInformation['senderId'] = result.userId;
usersInformation['ewalletId'] = result.ewalletId;
usersInformation['money'] = result.money;
getDestinationTakeMoneyUserInfo(data, function (success, result) {
usersInformation['destinationUserId'] = result.userId;
});
}
log.info(usersInformation);
});

Answer

You should use Promise

I give you an example

function getMoneySenderUserInfo(data) {

 var promise = new Promise( function(resolve, reject) {
   var query = "..."
   connection.query(query, function (err, results) {
     if (err || results.length === 0) {
       reject();
     } else {
       resolve(results[0]);
     }
   });

 return promise;
}

You have to do the same thing for getDestinationTakeMoneyUserInfo function

Then you can have your final result like this :

var usersInformation = {};
Promise.all([getMoneySenderUserInfo(data), getDestinationTakeMoneyUserInfo(data)])
.then(function (results) {
    usersInformation['senderId']  = results[0].userId;
    usersInformation['ewalletId'] = results[0].ewalletId;
    usersInformation['money']     = results[0].money;
    usersInformation['destinationUserId'] = result[1].userId;
});

As you can see Promise.all will wait for the two db requests, the callback (passed in the then function) will be called when the two promises will be resolved so you can finally retrieve the two results.

Comments