What methods can I use to implement dynamic callback parameters in JavaScript?

Is it possible to pass dynamic callback arguments in JavaScript functions?

I am trying to combine three different functions, aiming to streamline the process and minimize code repetition. You can see an example below:

const initDB = (schemas: any[]) =>
  Realm.open({ path: 'CircleYY.realm', schema: schemas })
    .then((realm: Realm) => ({ realm }))
    .catch((error: Error) => ({ error }));

This function initializes a database and returns either a database instance or an error.

I also have specific database write functions like the one shown here:

// Delete a message
const deleteOrder = (orderID: string, realm: Realm) => {
  realm.write(() => {
    const order = realm.objects('Orders').filtered(`primaryKey = ${id}`);
    realm.delete(order);
  });
};

In addition, there are three more functions as follows:

makeDBTransaction(deleteOrder(id));

and

makeDBTransaction(writeCommentInOrder(orderId, comment))

and

const makeDBTransaction = async (callback: Function) => {
  const { error, realm } = (await initDB([
    OrderSchema,
    ProductSchema,
  ])) as InitRealm;
  if (error) return { error };
  callback(realm); 
  return realm.close();
};

I am looking for a way to pass the realm into the callback with more than two arguments. How can I accomplish this task?

Answer №1

In my opinion, a useful approach is to store arguments in an array in a specific order and then pass them to a function when calling it.

//for instance

function exampleFunction1(a, b) {
  console.log(a, b);
}

function exampleFunction2(cb, b) {
  const a = 3;
  cb.apply(null, [a, b]);
}

exampleFunction2(exampleFunction1, 7);

//Your implementation might look like this
makeDatabaseTransaction(deleteRecord, [recordId]);

const makeDatabaseTransaction = async (callback: Function, args: any[]) => {
  const { err, db } = (await initializeDatabase([
    RecordSchema,
    UserSchema,
  ])) as DatabaseInitialization;
  if (err) return { err };
  args.push(db);
  callback.apply(null, args);
  return db.close();
};

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

Using AJAX to Display a Loading Image While Waiting for Database Query to Complete

I've been searching a lot for an answer to this question, but I haven't found the specific solution yet. Currently, I'm using the code below to execute a query. The processing time for the query can vary from 1 to 6 seconds or even more. Wh ...

Items set to "flex" will not stretch, and when they are set to "inline-flex," it causes the other items within

My challenge lies in getting an input box to expand across the entire width of the screen. Unfortunately, due to the elements it is enclosed within, the input box only occupies a small portion of the screen. Moreover, when it expands, it also pulls the sur ...

JS Button click functionality after page reload is inconsistent

I am currently working on an ASP.Net web app with a specific part that consists of three main pages: Main Page, Search User Page, and Edit User Page. The workflow for this section is as follows: After logging in, users are directed to the Main Page (Wo ...

Upon initializing mean.io assetmanager, a javascript error is encountered

I am eager to utilize the MEAN.io stack. I completed all the necessary initialization steps such as creating the folder, performing npm install, and obtaining the required libraries. Currently, in server/config/express.js file, I have the following code: ...

unable to save array using chrome extension storage API

Currently, I am in the process of developing a Chrome extension and utilizing the Storage API. The information regarding this can be found here. To my understanding, it is feasible to store JS objects and arrays through this method. Below is an excerpt of ...

Concealing/revealing placeholder text in Angular applications

Can anyone help me figure out how to display hint text below an input only if the input is error-free on $error? I've tried using ngShow/Hide and $valid/$invalid but it's not working as expected. <div ng-form="reg.form" name="reg.form" novali ...

Implementing a feature to store highscores in a database using AJAX

I have developed a canvas game that is integrated with a website. I am looking to implement a feature where the player's highscore is posted to a database that I have created. The relevant portion of my game script responsible for updating the highsco ...

What advantages can be gained from having multiple package.json files within a single application?

Embarking on the journey of creating my inaugural full react web application entirely from scratch. Previously, I've mainly worked on assignments that were partially pre-made for me. While setting up my project, I couldn't help but notice that I ...

Leveraging D3.js in combination with Total.js and node.js

I have been attempting to utilize total.js in conjunction with D3 for creating a tree visualization. However, I am encountering issues when trying to download D3. This is what I do: npm install D3 Upon running the above command, I receive the following e ...

hybrid application combining AngularJS with Angular 17 and above versions

I have been attempting to set up a hybrid environment with both AngularJS and Angular 1.7+ running side by side. I diligently followed all the guidelines and even created a custom webpack configuration to bundle my AngularJS and Angular files together. The ...

Ways to activate touch events in pjax library?

As I work on developing a website, I am utilizing the Pjax library, which is a port of jquery pjax. However, I have encountered an issue where touch events are not being processed. My implementation of Pjax looks like this: var pjax = new Pjax({ selectors ...

What is the best way to make an array with values from a checkbox list?

I am working on a project that involves rendering a list of products categorized into different categories. Users can select these categories using checkboxes. Are you interested in learning how to create an array containing the selected values from the ch ...

How to prompt the browser to download a file with a specific name using node.js and express

I've created a node/express website as part of my university project. It allows users to search for a specific law ID, which then displays a table with various files in different formats and languages related to that ID. I am using the "http-proxy" mo ...

Mastering Two-Way Binding in Angular 2 with JavaScript Date Objects

I am currently utilizing Angular 2 and have encountered the following code: Within the JS file, this code initializes the employee-variable for the template: handleEmployee(employee : Employee){ this.employee = employee; this.employee.sta ...

Adjustable Cursor - modify size while in motion at high speeds

I've designed a unique custom cursor and I am looking to enhance its functionality by adjusting its scale dynamically during fast movements. Similar to the cursor on this website: Example.com Here is my custom cursor for reference: CodeSandBox What ...

Creating a customized conditional overflow style in _document.js for Next.js

Is there a way to dynamically change the overflow style for the html and body elements based on the page being viewed? For instance, on the about page, I want to hide overflow for html but not for body, whereas on the contact page, I want to hide overflow ...

transferring information between two html pages using javascript

Although this question has been raised multiple times, I have gone through the answers and attempted various solutions, however, my code is still not functioning correctly. Below are my working files : my_app -index.html -task1 -index.html I ...

Transferring information between a service and a controller

I'm struggling to pass data between a service and a controller in my AngularJS project. Even though I've followed the recommended steps, the code is not functioning as expected. Below is the controller snippet: function udpController($scope ...

In JavaScript, update all child nodes with a class name attribute

Currently, I am utilizing Selenium Webdriver in my project. On a webpage of mine, there exists numerous menu items each containing sub menu items. My objective is to modify the classname attribute for all child elements located under the nav-left-main di ...

Module exists; however, command could not be located

I am experiencing an issue with the rimraf node module. Despite being able to access its folder within the node_modules directory, I am receiving errors indicating that the command for rimraf cannot be found. I have attempted to delete the entire node_mod ...