Using JavaScript to pass a newly created variable as an argument in a default

Currently, I am developing a node application that heavily utilizes promises. To enhance the readability of my code, I have been removing anonymous functions and storing them in a JavaScript object called "myCallbacks". Here's an example:

let myCallbacks = {
  myFirstCallback: function(fulfill, reject) {
    // Perform certain tasks
    if(noError)
      fulfill({field: 'data'});
    else
      reject('ERROR');
  },
  mySecondCallback: function(fulfill, reject) {
    // Perform certain tasks
    if(noError)
      fulfill({field: 'data'});
    else
      reject('ERROR');
  }
}

let myFirstMethod = function() {
  return new Promise(myCallbacks.myFirstCallback);
}

let mySecondMethod = function() {
  return new Promise(myCallbacks.mySecondCallback);
}

This approach has proven to be effective.

Now, I encountered a situation where I need to pass data to my callbacks. Let me provide you with an example:

let myCallbacks = {
  myFirstCallback: function(fulfill, reject) {
    // Perform certain tasks
    if(noError)
      fulfill({field: 'data'});
    else
      reject('ERROR');
  },
  mySecondCallback: function(fulfill, reject) {
    // Perform certain tasks
    if(noError)
      fulfill({field: 'data'});
    else
      reject('ERROR');
  },
  myThirdCallback: function(fulfill, reject, someVariable) {
    // Perform certain tasks
    if(someVariable*3>10)
      fulfill({field: 'data'});
    else
      reject('ERROR');
  }
}

let myFirstMethod = function() {
  return new Promise(myCallbacks.myFirstCallback);
}

let mySecondMethod = function() {
  return new Promise(myCallbacks.mySecondCallback);
}

let myThirdMethod = function(someVariable) {
  // This approach doesn't work
  return new Promise(myCallbacks.myThirdCallback);

  // This approach doesn't work either
  return new Promise(myCallbacks.myThirdCallback(fulfill, reject, someVariable));

  // Nor does this approach work
  return new Promise(myCallbacks.myThirdCallback(someVariable));
}

What is the correct way to pass "someVariable" from "myThirdMethod" to "myCallbacks.myThirdCallback()"?

Answer №1

Here's a suggestion for achieving your goal:

var anAlternativeCallback = function(parameter)
{
   return function(resolve, reject)
   {
     ... utilize the parameter and perform the necessary actions ...
   }
}

...

new Promise(anAlternativeCallback(value));

However, without a deeper comprehension of your specific objective, it's challenging to determine if this approach is suitable.

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

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Automatically scrolling down a div as new content is added using XMLHTTPRequest.openConnection

https://jsfiddle.net/kv5gbamg/ - I created a jsfiddle to demonstrate the functionality of the system Essentially, I am seeking a way to automatically scroll the scrollbar to the bottom every time a new message is received. My system updates the div with ...

Incorporating a delete button onto an image using JavaScript

I am currently developing a BlogApp and facing difficulty in attempting to include a button on an image. The image is being retrieved from the Django database in JavaScript (HTML). My goal is to have a clickable button overlaid on the image. views.py def ...

Secure User Authentication using HTML and JavaScript Box

In the given code, I am attempting to implement a functionality where a message is displayed next to the select box if it does not have a value of male or female. This message should not be shown if one of these values is selected. However, this feature ...

Ways to resolve the issue: "Mandatory aggregateBy parameter missing" in the fitness API

I'm struggling with an error that keeps popping up saying "Error: Require at least one aggregateby" and I have no idea how to resolve it. I've attempted several methods: fitness.users.dataset.aggregate({ auth: serviceAcc ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

Retrieving inquiries associated with a specific tag on Stack Overflow

I'm part of a team of developers in my Discord community who are dedicated to helping others with their problems on Stack Overflow. Is there a way to create a bot that can automatically gather the latest question tagged with a specific keyword and s ...

Identifying the specific promise that failed within a chain of .then statements

I am currently working on setting up a chain of promises with an error catch at the end within my node and express application. One issue I have encountered is that if any of the 'then' functions encounter an error, it can be difficult to trace b ...

Having trouble installing Puppeteer with npm due to permission denied errors?

Having trouble installing puppeteer as a project dependency, even after re-installing node. Seeking advice on how to resolve this issue. Currently running Ubuntu 17.10 x64. sudo apt-get purge nodejs; curl -sL https://deb.nodesource.com/setup_8.x | sudo -E ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

Managing Emails with Vue and Firestore

I am facing an issue with updating the 'email' field. Whenever I try to change the email address, it gets updated correctly. However, when I attempt to log in again, the new email address does not work; only the old one seems to be functional. Ho ...

You cannot use voice_channel.join() to create a music bot in discord.js v13

As I was working on a new music command feature for my Discord bot, I encountered an issue. Whenever I try to use the command -play {url}, I keep getting an error message that says: voice_channel.join is not a function. I searched through various resource ...

Encountering a "400 Bad Request" error when using Ajax within WordPress

I've been trying to submit a form using Ajax within a plugin. I had two plugins, the first one was initially working but has stopped now and I can't seem to find any errors. I don't think the issue lies in the code itself, but I'm feeli ...

Windows location does not change after an XMLHttpRequest is made

Here is my code that uses XMLHttpRequest: function SignUp() { signUpConnection = new XMLHttpRequest(); signUpConnection.onreadystatechange = processRegistration; signUpConnection.open('GET', 'index.php?registrarse=&username= ...

Unlock the Power of Core 2 MVC with the Cutting-edge Integration of

Looking for a solution on how to effectively use JQuery Datatables with Core MVC? Check out this helpful resource: Using jQuery DataTables Grid With ASP.NET CORE MVC I recently downloaded the sample project and made some modifications to fit my needs. It ...

Guide on transforming Div content to json format with the use of jquery

I am trying to figure out how to call the div id "con" when the export button is clicked in my HTML code. I want it to display JSON data in the console. If anyone has any suggestions or solutions, please help! <html> <div id ="con"> < ...

Explore vue3 components using vue-test-library and universal components

I started creating unit tests for a production app using jest, @testing-library/vue, and supporting libraries. The first test I created is as follows: import vue from "vue"; import { render } from "@testing-library/vue"; import LibBtn f ...

React Router - Implementing a <Redirect> element rather than a list of child components

Here is the code snippet I am working with: import { Redirect } from 'react-router-dom'; import QPContent from '../QPContent'; class AnswerContainer extends Component { constructor(props) { super(props); this.state = { ...

When using `Mongoose.find({})`, the result is an empty array

I'm having issues with my code where it's only returning an empty array when I try to fetch documents from the "Ingredients" collection. Here is a link to my "Ingredients" collection image: https://i.stack.imgur.com/Gpw8V.png Below is the ingre ...

Tips for customizing the time selector in material-ui-time-picker

Is there a way to enable keyboard input control for the material-ui-time-picker? Currently, it only allows editing when clicking on the clock interface. Here is a snippet of my code: import React, { Component } from "react"; import { TimePicker } from " ...