如何将参数传递给promise函数

问题描述 投票:62回答:2

这似乎是一个愚蠢的问题,但我是这个主题的新手。我正在研究节点js上的promises。我想将参数传递给promise函数。但是我无法理解。

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"));
  }
});
javascript node.js promise
2个回答
125
投票

将你的Promise包装在一个函数中,否则它将立即开始工作。另外,您可以将参数传递给函数:

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

然后,使用它:

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

ES6:

const someFunction = (username, password) => {
  return new Promise((resolve, reject) => {
    /*stuff using username, password*/

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

使用:

someModule.someFunction(username, password).then(uid => {
  /* stuff */
});

6
投票

其他方式:

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);
© www.soinside.com 2019 - 2024. All rights reserved.