This might seem a silly question but I am a newbie in this topic. I am working with Promises on Nodejs and I want to pass a parameter to a Promise function. However I could not figure it out how to do it.
For example:
someModule.someFunction.then(username, password,function(uid) {
/*stuff */
}
And the function is something like:
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"));
}
});
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
});