0

I'm trying to execute certain function depending on what I get from my database in app.rutine here:

return Promise.all(finalApps.map(app => {
       return counts.push(setRutine(**app.rutine**));
}))

And the trying to push the return of the function inside the counts Array as shown

But I keep getting Promise { } or Promise { undefined }

This is the setRutine async function:

async function setRutine(nameF) {
    if(nameF == "countUsers") {
        console.log("YES; IT IS");
        await countUsers().then((count) => {
            console.log("FROM IF STATEMENT: " + count);
            return count;
        })
    } else {
      return "";
    }
}

And this is the countUsers() function it calls if the info it got from the db is countUsers that returns a Promise

function countUsers() {
    var db = admin.firestore();
    var usersRef = db.collection('users');

    var count = {};

    return new Promise ((resolve, reject) => {
        return usersRef.get().then(function(querySnapshot) {      
            count.size = querySnapshot.size;
            count.id = "1";
        })
        .then(() => {
            console.log("FROM countFunction: " + count);
            resolve(count);
        })
        .catch((error) => {
            reject(error);
        })
    });
}

Thank you for any help!

Farid
  • 59
  • 8
  • 1
    What if `nameF ` is not equal to `countUsers `, then you are returning an undefined – felixmosh Aug 20 '18 at 20:48
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Aug 20 '18 at 20:49
  • 2
    There's just too many problems here. You're mixing async/await with then/catch, you've got an unnecessary use `new Promise`, and you're trying to push the return value of an async function into an array (which is always going to be a promise). You might want to consider reviewing how async/await actually works, as there is no simple fix here. – Doug Stevenson Aug 20 '18 at 20:54

2 Answers2

3

You have to return something from setRutine, probably the promises result:

 return await countUsers() /*...*/
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Thank you for all your answers, you all helped me a little to understand better my problem and Doug Stevenson was right I changed the setRutine function to return a Promise instead of being an async function.

I post the code:

function setRutine(nameF) {
    return new Promise( (resolve, reject) => {
        if(nameF == "countUsers") {
            return countUsers().then((count) => {
                resolve(count);
            }).catch((error) => {
                reject(error);
            })
        }
    });
}
Farid
  • 59
  • 8