JackJackson12
JackJackson12

Reputation: 27

async/await issue (returns undefined) mongoose

When I call the method interval, the parameter user, which I get from the method allUserStats, is always undefined. Here is the method

const interval = async () => {
    const allUsers = await getAllUser();
    for (const u of allUsers) {
            let user;
            let followerScore;
            let subscriberScore;
            //let hostsScore;
            let viewerScore;
            await getAllUserStats(u.login_name).then(async (userStats)=>{
                user = userStats;
...

The method getAllUserStats looks like this:

const getAllUserStats = async (login_name) => {
    await userstats.findOne({login_name}).then(async(userStats)=>{
        if(userStats===null){
            let user = new userstats({
                login_name:login_name,
                followers: [],
                subscribers: [],
                hosts: [],
                viewers: []
            })
            await user.save();
            return user;
        }
        else{
            return userStats;
        }
    })
}

I think it is an async-await issue, but I dont know. Any advice how I can fix that?

Upvotes: 1

Views: 83

Answers (1)

TKoL
TKoL

Reputation: 13892

You're mixing async/await and using promise.then -- you can just write it all with async/await that should make it easier:

const getAllUserStats = async (login_name) => {
    const userStats = await userstats.findOne({login_name})
    if(userStats===null){
        let user = new userstats({
            login_name:login_name,
            followers: [],
            subscribers: [],
            hosts: [],
            viewers: []
        })
        await user.save();
        return user;
    }
    else{
        return userStats;
    }
}

Upvotes: 1

Related Questions