0

I'm trying to build a service layer on top of mongo. I have a User object which has an array of referenced Achievements.

After I've authenticated the user by JWT or some other means, I enter the service layer and query the relationship as follows.

findForUser(userId: string | Types.ObjectId): Promise<Achievement[]> {
  return new Promise((resolve) => {
    UserSchema.findOne({ _id: userId },
      async (err: any, user: User) => {
        const AchievementMap: Achievement[] = [];

        if (err) throw new Error(err);
        user.achievements?.forEach((a) => {
          // @ts-ignore
          AchievementMap.push(a);
        });
        resolve(AchievementMap);
      });
  });
}

What is the async/await approach to returning the result of the callback method passed into UserSchema.findOne?

2 Answers 2

3

findOne returns an awaitable object - so you don't need to pass a callback to it. Don't try mixing callbacks with async/await. The only way to return the value from the callback, as a result of the constructed promise is by using resolve (only available in the promise executor).

Instead, make it all async - functionally similar but far cleaner.

async findForUser(userId: string | Types.ObjectId): Promise<Achievement[]> {
    const user = await UserSchema.findOne({ _id: userId });

    const AchievementMap: Achievement[] = [];
    user.achievements?.forEach(a => {
        AchievementMap.push(a);
    });
    return AchievementMap;
}
Sign up to request clarification or add additional context in comments.

Comments

3

What is the async/await approach to returning the result of the callback

The async and await keywords are tools to manage promises. They aren't tools to manage callbacks.

The entire point of the code you have in the question is to wrap a promise based API around a function that deals in callbacks.

Now you have a promise you can await the return value of findForUser.

You can't use async and await instead of creating a promise.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.