The Utilization of Callback Functions in CRUD Operations

I am curious about incorporating CRUD operations as callbacks while maintaining the Separation of Concerns.

For instance, I have written a function that retrieves all users:

UserService.js

function getUsers(callback) {

  User.find(function(err, users) {

    if (err) {
      console.log("Error during search: " + err)
      return callback(err, null)
    }
    console.log("All went well.");
    return callback(null, users);
  })
}

UserRoute.js

router.get('/publicUser', function(req, res, next) {

  userService.getUsers(function(err, result) {
    console.log("Result: " + result)
    if (result) {
      res.send(Object.values(result))
    } else {
      res.send("There were issues.")
    }
  })

})

In my opinion, a corresponding CRUD function that returns exactly one user without using a callback would look like this:

Userservice.js

function getByUserId(req, res, next) {

  let userID = req.body.userID;
  User.findOne({
    userID: userID
  }, function(err, result) {
    if (err) {
      console.log("Error during search: " + err)
    } else {

      console.log("All went well.");
      res.send(result)
    }
  })
}

UserRoute.js

router.post('/publicUser/getByUserID', userService.getByUserId)

What would the same function look like when using a callback?

Answer №1

Arrow functions are typically used for callbacks to maintain a clear Separation of Concerns.

For example, in UserRoute.js:

router.get('/publicUser', (req, res, next) => {
  userService.getUsers( (err, result) => {
    console.log("Result: " + result)
    if (result) {
      res.send(Object.values(result))
    } else {
      res.send("There was an issue.")
    }
  })

})

With arrow functions, there is no need to define a separate function for each callback, promoting better separation of concerns.

This is my first time providing an answer on stackoverflow, I hope the solution helps you understand :)

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

Clicking on the element will not cause the body to scroll

For some reason, I need to keep the onclick function, but I'm struggling to make it work as intended. What I want is for the body to slide to the next logo when the previous logo is clicked. This is a simplified version of what I have: <div class ...

Exploring the World of 3D Rotation with Three.js

I currently have 2 mesh objects - the Anchor and the Rod. The Anchor rotates around the z-axis, as shown in the image. The Rod is designed to only move backward and forwards. You can view the image here: . However, I am struggling to determine the matrix ...

Ways to efficiently incorporate data into App.vue from the constructor

My app initialization uses main.js in the following way, import App from './App.vue'; const store = { items: [{ todo: 'Clean Apartment.', },{ todo: 'Mow the lawn!', },{ todo: 'Pick up ...

Pause and check for the completion of data loading in mapstate

I have a stored userProfile in the Vuex state in order to access it throughout my project. However, when I try to use it in the created() hook, the profile is not loaded yet during the initial page load. Although the object exists, it does not contain any ...

Resolving dynamic table name issue in Prisma using current date

I'm currently facing a challenge with my MySQL querying function using Prisma in Express.js. The issue revolves around the interpretation or format of the currentDate parameter within this function: console.log('Operation successfully.&apo ...

Using AJAX (jQuery) to process and refine JSON data through filtration

I need assistance with filtering a JSON array using AJAX but I'm unsure of how to proceed. { posts: [{ "image": "images/bbtv.jpg", "group": "a" }, { "image": "images/grow.jpg", "group": "b" }, { "image": "images/tabs.jpg", ...

Is it possible to manage the form submission in React after being redirected by the server, along with receiving data

After the React front-end submits a form with a POST request to the backend, the server responds with a JSON object that contains HTML instead of redirecting as expected. How can I properly redirect the user to the page received from the server? For inst ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

Tips for creating a linear movement effect for a collection of objects

I am working on animating a linear gripping motion for picking and placing objects. Here is a codesandbox link where you can see the issue I am facing: https://i.sstatic.net/dUdPv.png The gripper is created, moves down to reach the LEGO brick, and then s ...

Morgan logging fails to exclude logging of keep-alive requests

I have a node.js express application running on AWS behind an Elastic Load Balancer, with 'morgan' as the logging mechanism. The ELB sends periodic keep-alive requests to a 1-character text file (keep-alive.txt). To prevent these requests from ...

Sorting by number or date in indexedDB may lead to unexpected results due to the

I have set up an index in my database called time on the created_at field: var os = thisDB.createObjectStore(name, { keyPath : "id" }); os.createIndex("time", "created_at", {unique: false }); Instead of storing the time as a standard date format, I conv ...

Using Node.js to build a RESTful API service

Recently, I developed an AngularJS application without utilizing Node.js. Instead, I opted to run the app locally using the "chrome-add server extension" and deployed the files on Bluemix cloud. In Bluemix, I created a Java service and used http.get to acc ...

A guide on handling POST response body parsing in NodeJS

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res){ res.sendFile(__dirname + "/index.html"); }); app.post("/", function(r ...

How to pass a variable or value through the async await API in the Vue.js and Laravel integration?

I'm facing an issue with my API where I want to check if a given email exists in the database, but every time I run it and view the console log, it returns undefined. Can anyone here suggest a better code snippet or approach for this? I specifically w ...

There are two identical instances of the function and class named "Ajax" within the prototype

Within the current project I am involved in, we have incorporated and utilized a function called Ajax repeatedly throughout various sections. function Ajax (recvType, waitId) I am considering implementing the "prototype framework" for the Ajax class. Sh ...

What is the function of the '#' symbol in Express routing?

Recently, I set up an Express server using backbone.js with a few routes in place. My goal is to capture information through the URL using req.params. The server has been configured with proper routing: app.get( '/route/:first/:second', router ...

Issue Detected at a Precise Line Number - Android Studio

Despite my numerous attempts to modify the specific line in question, including leaving it empty, turning it into a comment, or removing it entirely, the error message persists. I even went as far as deleting the class and creating a new one, but the same ...

Breaking the Boundaries of Fuzzy Search with JavaScript

I am currently utilizing ListJS's plugin for fuzzy search. It can be found at the following link: In an attempt to enhance the plugin, I implemented my own method to filter by the first letter of the items in the list. This involved selecting from an ...

"Troubleshooting the slow loading of PDF files when using React's render-pdf feature

After creating a table with the ability for each row to generate and download a PDF using render-pdf npm, I encountered an issue. When the user clicks the download button, the PDF preview opens on a new page. However, there are problems with rendering as a ...

React treats flat arrays and nested arrays in distinct ways

After some experimentation, I discovered an interesting behavior in React when passing nested arrays. Surprisingly, React renders the items properly without complaining about missing keys on the elements. const stuff = 'a,b,c'; // Nested Array ...