Skip to content
Advertisement

How to pass parameter to a promise function

this might seem a silly question but I am a newbie in this topic. I am working on promises on node js. And I want to pass parameter to a promise function. However I could not figure it out.

someModule.someFunction.then(username, password,function(uid) {
  /*stuff */
}

and the function is something like

var someFunction = new Promise(username, password, function(resolve, reject) {
  /*stuff using username, password*/
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
});

Advertisement

Answer

Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:

var some_function = function (username, password) {
  return new Promise(function (resolve, reject) {

    /* stuff using username, password */

    if (/* everything turned out fine */) {
      resolve("Stuff worked!");
    } else {
      reject(Error("It broke"));
    }
  });
};

Then, use it:

some_module.some_function(username, password).then(function (uid) {
  // stuff
});

 

ES6:

const some_function = (username, password) => {
  return new Promise((resolve, reject) => {

    /* stuff using username, password */

    if (/* everything turned out fine */) {
      resolve("Stuff worked!");
    } else {
      reject(Error("It broke"));
    }
  });
};

Use:

some_module.some_function(username, password).then((uid) => {
  // stuff
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement