如何将参数传递给promise函数

时间:2016-02-10 14:53:31

标签: javascript node.js promise

这似乎是一个愚蠢的问题,但我是这个主题的新手。我正在研究节点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"));
  }
});

5 个答案:

答案 0 :(得分:129)

将你的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 */
});

答案 1 :(得分:3)

更短

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

答案 2 :(得分:1)

您可以在带参数的函数中返回您的承诺。像这样:

function someFunction(username, password) {
      return new Promise((resolve, reject) => {
        // Do something with the params username and password...
        if ( /* everything turned out fine */ ) {
          resolve("Stuff worked!");
        } else {
          reject(Error("It didn't work!"));
        }
      });
    }
    
    someFunction(username, password)
      .then((result) => {
        // Do something...
      })
      .catch((err) => {
        // Handle the error...
      });

答案 3 :(得分:0)

您可以使用.bind()将参数( this )传递给函数。

var someFunction =function(resolve, reject) {
  /* get username, password*/
  var username=this.username;
  var password=this.password;
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));

答案 4 :(得分:0)

我用这个..

let verifyEmail = (email) => new Promise((resolve, rejected) => {
    let rsp = {isRepeated:false}
    let sql = `select id from users where email='${email}' `
    try{
        db.query(sql, (err,result)=>{
            if(!err){
                if(result.length > 0){
                    rsp = {isRepeated:true}
                }
            }
        })
        resolve(rsp)
    }catch(e){
        rejected({ok:false,err:e})
    }
})