0

The function findTransactionByBill find the results but it returns as undefined when I call it from inside the app.post.

function findTransactionByBill(billId){
   Transactions.find({billId : billId},function(err, transactions){
        if(err)
            res.send("Error: "+err);
        console.log(transactions); //Returns the results
        return transactions; // <--- Doesn't send the results to the trans variable inside the app.post below!
    }); 
}

app.post('/api/transaction', function(req, res) {
    trans = findTransactionByBill(req.body._id);
    console.log("Transactions: "+trans);
    Transactions.create({
        billId       : req.body._id,
        paymentDate  : Date.now(),
        amount       : req.body.amount,
        timestamp    : Date.now()

    }, function(err, transactions) {
        if (err)
            res.send(err);

        res.send(transactions);
        });
    });

When I log the transactions variable, it returns the result. But when I call it from inside the app.post (trans) it display as undefined...

All I'm trying to do is: 1) Have a common function which I can use to check if that transaction already exists. 2) Use it from any place in the application.

Maybe the way I'm using the function is wrong. Thanks in advance for the help!

Deisy Laymi
  • 343
  • 1
  • 2
  • 10
  • 1
    `findTransactionByBill` returns nothing. It calls `Transactions.find` which is passed a function as its second parameter that returns something. – marekful Dec 27 '14 at 11:26
  • @MarcellFülöp If I change it to a function (see edited), it doesnt work as well. I think it has something todo with Asynch which I don't know how it works. But thats just my guess. Any help is appreciated. Thanks! – Deisy Laymi Dec 27 '14 at 11:36
  • I [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) I will help – Alberto Bonsanto Dec 27 '14 at 11:38

0 Answers0