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

I am currently working on creating a system for displaying rating stars for products. The rating value, which ranges from 0 to 5, has already been provided

class PostBodyRatingStars extends React.Component { render() { const { classes } = this.props var rating = this.props.rating function createMappingArray(rating) { var arr = [] for (i = 0; i < 5; i++) { if (rating >= ...

Limiting access to all routes except one

Lately, I've been exploring the combination of ExpressJS + AngularJS and encountered a bit of a tricky situation. My objective is to create a single login page and a dashboard page. By using Passport + MongoDB for user authentication, my plan is to v ...

Change not accepted

I am a beginner in Angular and still grappling with the fundamentals. On my menu, I have a cart icon with an initial value of 0 upon first load. In my product list, each product has an 'AddToCart' button. What I aim to achieve is- I want to dy ...

A Guide to Effectively Extracting Data from Second Level JSON Arrays with

Hi, I'm having difficulty fetching the two attributes under CategoryImage in the second level of the JSON array parsing. Can someone help me with this? Thank you. <script> $(document).ready(function() { var cat=""; ...

Update the content of the document element by assigning it a lengthy string

I'm utilizing JQuery to dynamically assign content to a div element. The content has numerous lines with specific spacing, so this is the approach I am taking: document.getElementById('body').innerHTML = "Front-End Developer: A <br/> ...

Designing Object-Oriented JavaScript

Currently, I am in the process of developing a sophisticated JavaScript application. Utilizing an object-oriented design approach, I have organized my code into various files to enhance maintainability. In order to create my application, what is the best ...

After the jquery.show function is executed, an unexpected WebDriverException occurred, indicating an unknown error that prevents focusing

Here is my line of JavaScript code: $('#name').show(); And this is my webdriver code line: wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("name"))).sendKeys("Some Name"); When running the test, I encountered an exception: Web ...

Neglecting to pass data to the controller through the onclick function

Using this specific button element in my JavaScript implementation has raised some concerns. <button id="bid" type="button" class="button" onclick="connect()">Save</button> While I have noticed that it displays an alert message when 'ale ...

Using iOS to send a request - Receiving a response with a 304 HTTP status code from

I am currently in the process of developing an application specifically designed for iPad users. To create this app, I am utilizing Express and a restful approach as the backend framework. The code snippet below demonstrates how Express should respond on t ...

wait until the CSS parser retrieves the CSS files

I am trying to ensure that the page is rendered only after the CSS has been loaded. The function css_parser.getCSSFiles() reads the file asynchronously and sends the CSS content to the variable css.cssFile. How can I make sure that res.render waits for t ...

Executing untrusted JavaScript code on a server using a secure sandbox environment

I am facing difficulties in creating a secure node sandbox that can execute untrusted code while allowing users to communicate with the program through api calls (input and output). My goal is to establish a browser console where users can run their own se ...

Choosing the right framework for implementing push notifications can be a critical decision. Should

I am currently working on a Java application that requires the server to send push notifications to the client every one second. To achieve this, I am using HTML5 server-sent events for one-way communication from the server to the client. However, my conce ...

What is the best way to record data while initiating a process in node.js?

In my latest project, I have implemented a function that spawns a process and requires logging specific information to the console. Here is an example of how this function is structured: function processData(number) { var fileName = settings.file || "de ...

Express.js server not responding to http requests

I find myself scratching my head over this. Recently, I ventured into learning expressjs and currently, I am working on a website that serves as a proxy to retrieve data from other parcel websites. Upon using Postman, here is what I observed: https://i. ...

encountering a problem with permissions while attempting to update npm

Has anyone encountered a permission error with npm when trying to update to the latest version? I recently tried updating npm and received this error message. I'm unsure of how to resolve it. Any suggestions? marshalls-MacBook-Air:Desktop marshall$ n ...

The JavaScript function is returning a value of undefined

I encountered an issue where my Javascript function is returning undefined even though it alerts the correct value within the function itself. I have a setup where I call the function in my 1st controller like this: CustomerService.setName(data.name); A ...

I have an HTML table with multiple cells containing inner HTML tables. I have implemented a function along with buttons to filter the main table, excluding the inner tables

My HTML Table is generated from my database, containing information about machines and their status pulled from emails with HTML Tables. Each row has a click option to open/hide the <td> tag showing the original table for more details and better trac ...

What causes the issue when attempting to import multiple CSS files in a Vue.js project using @import more than once?

Currently, I am working on a project that involves one main component and several child components. These components require custom CSS files as well as additional vendor CSS files. A challenge I encountered is that I cannot use the @import "path/to/css/fi ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

Why does the header still show content-type as text/plain even after being set to application/json?

When using fetch() to send JSON data, my code looks like this: var data = { name: this.state.name, password: this.state.password } fetch('http://localhost:3001/register/paitent', { method: 'POST&a ...