0

I'm writing a node application which uses a lot of promises. In an effort to keep my code readable I'm removing as many anonymous functions as possible and storing them in one JavaScript object like the following.

let myCallbacks = {
  myFirstCallback: function(fulfill, reject) {
    // Do some stuff
    if(noError)
      fulfill({field: 'data'});
    else
      reject('ERROR');
  },
  mySecondCallback: function(fulfill, reject) {
    // Do some stuff
    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 works perfect.

Now I have a function where I need to pass data to my callbacks. Imagine the following code

let myCallbacks = {
  myFirstCallback: function(fulfill, reject) {
    // Do some stuff
    if(noError)
      fulfill({field: 'data'});
    else
      reject('ERROR');
  },
  mySecondCallback: function(fulfill, reject) {
    // Do some stuff
    if(noError)
      fulfill({field: 'data'});
    else
      reject('ERROR');
  },
  myThirdCallback: function(fulfill, reject, someVariable) {
    // Do some stuff
    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) {
  // Doesn't work
  return new Promise(myCallbacks.myThirdCallback);

  // Doesn't work
  return new Promise(myCallbacks.myThirdCallback(fulfill, reject, someVariable);

  // Doesn't work
  return new Promise(myCallbacks.myThirdCallback(someVariable));
}

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

user316114
  • 803
  • 7
  • 18
  • First and foremost you have some syntax errors when calling `myCallbacks.myThirdCallback`. You need to close the `new Promise` with the closing `)` at the end. – edwarddamato Mar 08 '17 at 22:41
  • Thank you, corrected. I just typed this out real quick as a much easier example of what I'm trying to do. – user316114 Mar 08 '17 at 22:44

1 Answers1

0

You could do the following:

var thatOtherCallback = function(variable)
{
   return function(fulfill, reject)
   {
     ... use variable and do whatever you need to do ...
   }
}

...

new Promise(thatOtherCallback(value));

But without a clearer understanding of what you're trying to achieve, it's difficult to say whether this is a good solution.

jcaron
  • 17,302
  • 6
  • 32
  • 46