如何将参数传递给承诺函数

这似乎是一个愚蠢的问题,但我是这个话题的新手。我正在节点js上做承诺。我想将参数传递给一个承诺函数。然而,我无法弄清楚。

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

函数是这样的

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"));
  }
});

答案 1

将承诺包装在函数中,否则它将立即开始完成其工作。另外,您可以将参数传递给函数:

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"));
  }
 });
}

然后,使用它:

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"));
  }
 });
};

用:

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

答案 2

另一种方法(必须尝试):

var promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});
var extraData = 'ImExtraData';
promise1.then(function(value) {
  console.log(value, extraData);
  // expected output: "Success!" "ImExtraData"
}, extraData);