Mr.D
Mr.D

Reputation: 7873

NodeJS, get return value from async await

I have an async await function that uses mongoose:

const createModelB = async (id) => {
    try {
        let user = await User.findOne({id: id});

        if (user) {
            let modelB = new ModelB({ user_id: user.id });
            modelB = await scrum.save();
            return modelB;
        }
        return null;
    } catch (err) {
        console.error(err);
    }

    return null;
};

Now then I'm calling this function from somewhere else:

let modelB = createModelB(123);
console.log(modelB);

Instead of outputting Models fields, console returns to me this:

Promise {<pending>}

What did I miss?

Upvotes: 2

Views: 6465

Answers (1)

akshay
akshay

Reputation: 517

I think it will be

const createModelBInstance = async () => {
 let modelB = await createModelB(123);
 console.log(modelB);
}

createModelBInstance();

as long as async functions are returning values you have to call an await on them, and should be wrapped inside another async function.

Upvotes: 6

Related Questions