0

I have a problem with my code. Any solution that I found are unclear to me.. I want to get a value by returning it by fethcing my database but obviously I don't handle my callback well.

Here is my code :

nbr_users = (key) => {
    db.User.find({
        shop: key
    }, (err, users) => {
        if (err) res.json(err)
        else
            return users.length //it's the value I want
    })
}

module.exports = (req, res) => {
    db.Account.find({}, (err, accounts) => {
        if (err) res.json(err)
        else {
            var accountMap = {}
            var i = 0;
            accounts.forEach((account) => {
                accountMap[i++] = {
                    users: nbr_users(account.key) //here I call my function
                }
            });
            res.json({user_list: accountMap})
        }
    })
}

EDIT: I don't know how to use async/await I try this, I have no idea about how to fix it

function getUsers(key) {
    return new Promise(function(resolve, reject) {
        db.User.find({
            shop: key
        }, (err, users) => {
            if (err) res.json(err)
            else
                resolve(users.length)
        })
    })
}

nbr_users = (key) => {
    return await getUsers(key)
}

module.exports = (req, res) => {
    db.Account.find({},
    (err, accounts) => {
        if (err) res.json(err)
        else {
            var accountMap = {}
            var i = 0;
            accounts.forEach((account) => {
                accountMap[i++] = {
                    users: nbr_users(account.key)
                }
              });
            res.json({user_list: accountMap})
        }
    })
}
Rbejot
  • 57
  • 1
  • 1
  • 10
  • Your in the world of `async` calls, IOW: you cannot get results returned inline. Good news, things like `Promise`'s, and `async / await` are here to help.. If you look into these, you will find the above much easier to code. – Keith Apr 23 '18 at 13:45
  • @Keith I just edited my answer, can you check what is the problem ? – Rbejot Apr 23 '18 at 14:21
  • Unfortunately answer has been marked as duplicate so unable to post an answer, but the duplicate link has some useful information on how you can do this. If your still having trouble implementing this after reading the duplicate, what I would suggest is you post another question asking help on how you could get your code working with `async` / `await`. – Keith Apr 23 '18 at 14:39
  • ok thank you I will do that ! – Rbejot Apr 23 '18 at 14:41

0 Answers0