如何将参数传递给Promise?

问题描述 投票:0回答:8

这似乎是一个愚蠢的问题,但我是这个主题的新手。我正在 Nodejs 上使用 Promise,并且想将参数传递给 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 parameter-passing es6-promise
8个回答
392
投票

将您的 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
});

11
投票

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

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


8
投票

更短

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

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

7
投票

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

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

5
投票

我知道这已经很旧了,但这可能会帮助人们通过谷歌进行挖掘。这是一个更实际的示例,我只需将 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);

5
投票

不确定是否理解正确,但为了将 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)
})


4
投票

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

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