如何将参数传递给 promise 函数

How to pass parameter to a promise function

这似乎是一个愚蠢的问题,但我是这个主题的新手。我正在致力于节点 js 的承诺。我想将参数传递给 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"));
  }
});

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

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

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

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

您可以使用 .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"}));

更短

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

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

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

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

我用这个..

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

我知道这已经过时了,但这可能有助于有人深入挖掘 google。这是一个更实际的例子,我只是将 2 个参数传递给一个 promise 函数并等待它解析。希望这会有所帮助。 setTimeout 模拟“处理时间”。 3 秒后,该值将从 promise 返回并打印到屏幕。

const addNumbers = (a, b) => {
    
  return new Promise((resolve, reject) => {
    
    setTimeout(() => {
      resolve(a + b);
    }, 3000);
  
  });
  
  
};

let getResult = async (a, b) => {
    let value = await addNumbers(a, b);
    console.log(value);
};

getResult(1, 3);

不确定是否理解正确,但为了将参数从 promise 发送到另一个函数,您可以这样做:

function logUser(username, password){
    return new Promise((resolve, reject) => {
        let response = 'user logged in'
        resolve(response)
    })
}

function showMessage(msg){
    console.log(msg)
}

logUser('user', 'pass').then((respFromLogUser) => {
    showMessage(respFromLogUser)
})