How to pass parameter to a promise function
Solution 1:
Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:
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"));
}
});
}
Then, use it:
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"));
}
});
};
Use:
some_module.some_function(username, password).then(uid =>
{
// stuff
});
Solution 2:
Another way(Must Try):
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);
Solution 3:
Even shorter
var foo = (user, pass) =>
new Promise((resolve, reject) => {
if (/* condition */) {
resolve("Fine");
} else {
reject("Error message");
}
});
foo(user, pass).then(result => {
/* process */
});
Solution 4:
You can use .bind() to pass the param(this) to the function.
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"}));