Leveraging async/await in conjunction with callback functions

I am in the process of creating a service layer on top of mongoDB. I have a User object that contains an array of referenced Achievements.

Once the user is authenticated using JWT or another method, I go into the service layer and retrieve the relationship in the following way.

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);
      });
  });
}

How can I implement the async/await approach to handle the callback function passed to UserSchema.findOne?

Answer №1

findOne provides an awaitable result, eliminating the need for a callback function. Avoid mixing callbacks with async/await as it can lead to confusion. The best way to retrieve data from a promise is by utilizing resolve within the promise executor.

Consider refactoring your code to be entirely async for a cleaner and more streamlined approach:

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

    const achievementList: Achievement[] = [];
    user.achievements?.forEach(achievement => {
        achievementList.push(achievement);
    });
    return achievementList;
}

Answer №2

What is the async/await method for handling callback results?

Using the async and await keywords allows for better management of promises, not callbacks.

The goal of the code provided is to incorporate a promise-based approach into a function that originally used callbacks.

Now with a promise in place, you can easily await the output of the findForUser function.

It's important to note that using async and await does not replace the need to create a promise.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transform a JSON object from a remote source into an Array using JavaScript?

Attempting to transform the JSON object retrieved from my Icecast server into an array for easy access to current listener statistics to display in HTML. Below is the JavaScript code being used: const endpoint = 'http://stream.8k.nz:8000/status-json ...

How to attach a listener to an ASP.NET control with jQuery

Looking for a way to detect user interaction with a checkbook list, text box, or drop down list, and style other elements based on the values present. Is there a way to achieve this using jQuery? ...

Tips for transferring a boolean value to a generic parameter in Java?

Looking to pass a boolean value to the Generic type in order to be utilized within a condition. This is the generic type interface OptionTypeBase { [key: string]: any; } type OptionsType<OptionType extends OptionTypeBase> = ReadonlyArray<Opt ...

The challenges of updating AngularJS partial templates and handling refresh in 2-way binding

I've encountered an issue with a partial template that's loaded outside of my ng-view, complete with its own controller. Here's a breakdown. Basic template layout <html ng-app="myApp"> ... <div ng-include src="'myPartia ...

Save the current layout in a cookie

We are utilizing three.js to display 3D representations of stomach contents based on MRI data. The colors represent approximate concentrations, with each bubble representing a voxel in the 3D space. Use the menu on the left to load different views. (Feel ...

Searching for a specific row of data by ID in a massive CSV file using Node.js

Can someone recommend an npm package that is ideal for iterating over a csv file, locating a specific value, and updating/appending to that particular row? I don't have any code to display at the moment as I'm in the process of testing different ...

Encountering an issue with subscribing wait times

Whenever a button is clicked within my application, I have a requirement to upload specific items to the API before proceeding with the next functionality. I've experimented with various approaches to ensure that the code waits for execution, but it ...

Ordering aggregate results by multiple fields with Mongoose

Here is a query using mongoose that I need help with: MinutesSpentStudying.aggregate([ { $match: { connected_user_id: ObjectId(user_id) } }, { $project: { minutes_spent_studying: 1, year: { $year: "$date" }, ...

I am looking to transfer information in CodeIgniter from a view utilizing AJAX post, handle that information in the controller, and then return the resultant array back to the view

I have been searching the entire internet, but unfortunately, I couldn't find a helpful solution. Any assistance would be greatly appreciated. Thank you in advance. MY HTML <div class="row"> I am unsure whether the form tag is required in my ...

VueJS and Vite: Encountering an unexpected character '�' while attempting to import files that are not JavaScript. Keep in mind that plugins are required for importing such files

I'm puzzled by the error message I'm receiving: [commonjs--resolver] Unexpected character '�' (Note that you need plugins to import files that are not JavaScript) file: /..../..../WebProjects/..../ProjectName/node_modules/fsevents/fse ...

Can you please send me the understanding? (hubot-script)

After setting up hubot and running some tests, I came across something puzzling: Looking at the following code snippet (from the maps.coffee file in hubot-maps) robot.respond /(?:(satellite|terrain|hybrid)[- ])?map( me)? (.+)/i, (msg) -> mapType = ms ...

Is it possible to authenticate a user in Firebase using Node.js without utilizing the client side?

Can I access Firebase client functions like signInWithEmailAndPassword in the Firebase SDK on the server side? Although SDKs are typically used for servers and clients use JavaScript, I need a non-JavaScript solution on the client side. I have set up the ...

Is there a way for me to transfer the value of a variable from one div to another within the same template?

I'm working on fetching data from a model object using a loop. My goal is to pass the same variable i between two separate div elements. I need the same i value because it's crucial for accessing the correct object. As someone new to this field, ...

Incorporating Three.js and Collada Loader to modify specific sections of a model within a .dae file

In my current project, I am using the Elf Girl model provided by three.js as an example. You can check out the model here. I am looking to replace the image with this CE2 image instead of the original CE image. ...

Utilizing THREE.JS Raycaster with JavaScript "entities" rather than just meshes

I am facing a challenge with the Raycaster model. I grasp the concept of how it intersects meshes that can be transformed, but my issue lies in identifying when the specific instance of an object is clicked. Consider a scenario where there is a button. Th ...

The user is defined, but the user's user ID is not specified

It seems that the user is defined, but user.user_id is not. My framework of choice is express.js and passport.js. router.post('/requestSale', function(req,res){ console.log('session user: ' + req.session.passport.user); //logs ...

Style binding for background image can utilize computed properties or data for dynamic rendering

In my code, I am trying to pass an object that contains a string path for its background image. I have experimented with using data and computed properties, but so far I haven't had any luck getting them to work within the :style binding. However, if ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

Facing issues with ng-options duplication?

I have provided the code below that I would like to display: $scope.states="India"; $scope.cities="Madhya Pradesh"; $scope.city="Ajmer"; When attempting to implement this in a cascading dropdown format, I encountered an error. You can find my jsfidd ...