Sending an additional parameter to a callback function

I am currently working on enhancing the functionality of my custom logging system for DB operations. My goal is to generate a more visually appealing and organized format in the console by adding an additional variable called operationName to the log messages upon completion of a DB operation.

// Customized Logger (Simplified)
const dbLogger = (error, data, operationName) => {
  if (error) {
    console.log(`${operationName} failed`, error)
  }
  console.log(`${operationName} success`, data)
}

// MongoDB Operations
import ChatModel from 'somewhere';

function createMessage() {
  const newChatAdded = new ChatModel({
    message: 'Hi'
  })
  ChatModel.save(newChatAdded, dbLogger);
}

In this setup, the callback parameters error and data are passed by the ChatModel.save method. However, my intention is to introduce a third parameter operationName (e.g., 'save' or 'delete') to further customize the log messages.

Answer №1

There are two options to choose from!

  1. Option 1: Utilize an anonymous function with a rest parameter and utilize spread when calling dbLogger:

    ChatModel.save(newChatAdded, (...args) => dbLogger(...args, "save");
    
  2. Option 2: Use a bound function:

    Modify the signature of your dbLogger function to include operationName as the first argument:

    const dbLogger = (operationName, error, data) => {
      if (error) {
        console.log(`${operationName} failed`, error)
      }
      console.log(`${operationName} success`, data)
    }
    

    Create a new bound log function that will always be called with "save" as the first argument.

    ChatModel.save(newChatAdded, dbLogger.bind(null, "save");
    

    This technique is also known as "partial application".

Answer №2

Save the new chat in ChatModel and log any errors using dbLogger.

To make it more concise, you can rearrange the parameters like this:

const dbLogger = (operationName, error, data) => ...

ChatModel.save(newChatAdded, dbLogger.bind(null, 'save'));

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

Understanding jest.mock: Verifying the invocation of a nested function

I have a section of code in my application that looks like this: import validationSchema from "./../_validation/report"; const reportModel = require("../models/report"); ctrl.addReport = async (req, res) => { const { body } = req; try { cons ...

Calculating distinct values within a single key in an object

My goal is to track the occurrences of four specific string values within the same key. The issue lies in my struggle with adding multiple counters. While the first counter successfully tracks the initial condition, subsequent conditions within the if/els ...

Can you create reusable components in Wordpress that are encapsulated?

In my quest to explore innovative approaches to Wordpress theme development, I have stumbled upon a variety of options such as the "Roots Sage" starter theme, the "Themosis Framework," and "Flynt." While these solutions address intriguing problems, they do ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

Is `console.log()` considered a native function in JavaScript?

Currently, I am utilizing AngularJS for my project. The project only includes the angular.min.js file without any additional references to other JavaScript files. The code snippet responsible for sending requests to the server is as shown below: var app = ...

Having trouble with executing Mongo import through shell script

I've been attempting to utilize a bash script to import JSON data, but it's not functioning correctly. The error message I'm encountering is: error validating settings: incompatible options: --file and positional argument(s) Here is the co ...

I constantly encounter a TypeError message that returns as undefined

I'm currently facing an issue while trying to run my Node.js server locally. The error message I keep receiving is: /Users/rogerjorns/Desktop/templateassignment/node_modules/express/lib/router/index.js:458 throw new TypeError('Router.use() ...

The issues with VUE3 compounding filters are causing unexpected results

Currently, I am attempting to filter search results using multiple filter options. After trying various methods, I have found that when applying only 2 filters, the search works as expected. However, when adding 3 or more filters, it includes additional re ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...

Attaching to directive parameters

I've been working on creating a draggable div with the ability to bind its location for further use. I'm aiming to have multiple draggable elements on the page. Currently, I've implemented a 'dragable' attribute directive that allo ...

Simulated function invocation just one time

I am testing the functionality of two functions in the same file. One of the functions is supposed to call the other, and I need to verify that this interaction occurs. import * as strings from './strings'; const generateUuidSpy = jest.spyOn(st ...

Retrieve the initial value from the TextField

My website features multiple filters, including by date and duration, allowing users to easily find the information they need from a large dataset. There is also a "reset all filters" button that clears all filters and displays the full list of products. ...

What is causing the javascript in my svg files not to function when embedded in an html document?

I have the following code for an SVG: <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="470px" height="260px" version="1.1" onload="addEvent ...

Transforming JSON information into a Backbone Model accompanied by a child Collection

Currently, I am dealing with a Playlist object that comes with various properties to define itself, along with a collection of PlaylistItems. Upon receiving data from the server, the JSON response is processed in the client-side success method: success: ...

Identifying Canvas Scrolling in iOS Safari using the Touchmove Event

I have encountered an issue while trying to detect scroll canvas from a touchmove event. It works perfectly on all browsers except for Safari. In Safari, the pageY and screenY coordinates of the touchmove event are not consistent. When I touch and move d ...

Adjust the style of an element when hovering over a different element

Below is the HTML code in question: <div> class="module-title" <h2 class="title" style="visibility: visible;"> <span>Spantext</span> Nonspantext </h2> </div> I am looking to change th ...

Divs expanding below content in IE on a particular server

Currently, I am facing an issue with a JavaScript div that expands correctly over other content in most situations but goes under the content in one specific scenario. I am unsure about where to begin debugging this problem. To provide some context, the d ...

Encountering an 'Unknown provider' error while running a unit test with AngularJS and Jasmine

I am facing an issue while writing a unit test for a controller in my application. Jasmine is showing an 'Unknown provider' error related to a provider I created for fetching template URLs. This provider is injected into a config function that is ...

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...

Determine if the input value is an integer using a custom validator in Angular 2

Looking for a way to validate integer inputs in an Angular2 project? I experimented with using Number(control.value), but it returns 0 for empty fields, which is not ideal. Another method I tried was parseInt(control.value,10), but it ignores spaces. For ...