0

I made a function and i wanted it to return true or false depending on some conditions:

var functions = {
BalanceTopUp:   function(value, user, referenceCode, date, madeby){
    var newInvoice = {
        type: "BalanceTopUp",
        value: value,
        balance_before: user.balance,
        balance_after: (user.balance*100000 + value*100000)/100000,
        date: date,
        forUser: user.code,
        referenceCode: referenceCode,
        made_by_user: madeby.code
    };
    Invoice.find({referenceCode: referenceCode},  function(erR, invoices){
        if(!erR){
            if(invoices.length === 0){
                Invoice.create(newInvoice,  function(error1, created){
                    if(!error1){
                        MoneyInvoice.find({referenceCode: referenceCode}, function(err, found){
                            if(found[0].status == 2){
                                return true
                            }else{
                                return false
                            }
                        })
                    }else{
                        console.log(error1);
                        return false
                    }
                });
            }else{
                return false
            }
        }else{
            console.log(erR)
            return false
        }
    })
    
}

when i try to call that function like that:

        console.log(await functions.BalanceTopUp(100, student[0], 5200225958146, moment().format("DD/MM/YYYY - h:mm:ss a"), student[0]))

it returns undefined, i think the problem is for scopes but i couldnt solve it, thanks in advance

mmostafa
  • 25
  • 6

1 Answers1

1

You have no return in the BalanceTopUp function, that is why you get undefined. And await is not necessary.

Robert Cojocaru
  • 106
  • 1
  • 5
  • thats why i am asking, how to make return in balancetopup function with the same conditions? – mmostafa Apr 13 '22 at 21:51
  • What conditions? You want to return `true` if it finds the item? – Robert Cojocaru Apr 13 '22 at 21:53
  • yes, i want to return true if found[0].status == 2, else will return false – mmostafa Apr 13 '22 at 21:55
  • Then do `const found = Invoice.find({.....` and at the end of the function do `return found != undefined` – Robert Cojocaru Apr 13 '22 at 21:57
  • noway to make it like i did it, like assigning true to a variable then returning in global scope? – mmostafa Apr 13 '22 at 22:11
  • You are using `find` method, the `find()` method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, `undefined` is returned [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). You need to get the result of the find method to check if you should return true or false. – Robert Cojocaru Apr 13 '22 at 22:18