You are missing two returns. Also, you have the function inside the e.forEach async which means it will run after the rest of your code so you won't get your result, remove that (since you aren't doing anything async there anyway):
const login = (db, token) => {
// v HERE v - you need to return the promise
return db.collection('users').get().then(async (e) => {
var i = []
// v HERE v - no async
e.forEach((doc) => {
if (doc.data().access_token === token){
i.push(doc.data().id)
// Also, no need for a return here, since it doesn't do anything
}
})
if (i.length === 0) return false
return i // << instead, here was another return missing
}).catch((error) => {
return false
})
}
module.exports = login
A clearer way would be to make login also async, then you could just use await there as well:
async function login (db, token) {
try {
const e = await db.collection('users').get()
const i = []
for (const doc of e) {
if (doc.data().access_token === token){
i.push(doc.data().id)
}
}
if (i.length === 0) return false
return i
} catch (e) {
return false
}
}
module.exports = login
This could be further simplified:
async function login (db, token) {
try {
const matchingUserIds = await db.collection('users').get()
.map(doc => doc.data())
.filter(docData => docData.access_token === token)
.map(docData => docData.id)
return matchingUserIds.length ? matchingUserIds : false
} catch (e) {
return false
}
}
module.exports = login
(I wonder though if there isn't any better method to filter the users by access token in your database. Right now it seems like you'll fetch all users and then check for the token in this function; it would probably be more scalable to query the database by token in the first place.)