0

I am learning NodeJS currently working on my first project a subscription based website.

I need a condition which decides whether one transaction has value at its btcTx property. This is done so when user creates a new transaction, BTC transaction gets created and added to the transactions .btcTx property. After the user presses F5 it should not create a new transaction but rather use the one already created. I have function that requires one argument a value of ID.

function tranHasBTC(tranId) {
    Transaction.findById(tranId,function(err,foundTr){
        if(err){
            console.log(err);
        } else {
            return (foundTr.btcTx != undefined);
        }
    });
}

This function is supposed to look in mongoDB database and look if transaction passed within argument has value at btcTx.

Then here I have the function which should rely on the upper functions return value

router.get("/btc/:txId", function (req, res) {
    var tranId = req.params.txId;
    var tranTrue = tranHasBTC(tranId);

    if (!tranTrue) {
       //add new transaction
    } else {
        //find transaction in database and load it from there
    }
});

The problem is that whenever the

var tranTrue = tranHasBTC(tranId);

gets called, it return undefined

I am assuming that I need to use some kind of async function to wait for the method to return either true or false, I have tried it with promises but I couldn't get it done, that is why I am posting here.

yivi
  • 42,438
  • 18
  • 116
  • 138
  • 2
    You could provide a callback to the `tranHasBTC` which is invoked inside when you have a result. OR return a promise inside the `tranHasBTC` function OR use the 'new' async/await functionality provided by ES6. – Luke Stoward Dec 18 '17 at 11:09
  • hi, you should use callback method, you should call tranHasBTC function and return a callback. and your if conditions or further process will be in that call back function eg- `function tranHasBTC(tranId, cb) { Transaction.findById(tranId,function(err,foundTr){ if(err){ console.log(err); } else { cb(foundTr.btcTx) } }); } router.get("/btc/:txId", function (req, res) { tranHasBTC(tranId, function(value){ if (!tranTrue) { //add new transaction } else { //find transaction in database and load it from there } }); });` – Himanshu Sharma Dec 18 '17 at 13:17

0 Answers0