Sometimes, we want to pass parameters to a promise function with JavaScript.
In this article, we’ll look at how to pass parameters to a promise function with JavaScript.
How to pass parameters to a promise function with JavaScript?
To pass parameters to a promise function with JavaScript, we can create a function that takes the parameters we want to returns the promise.
For instance, we write
const f = (username, password) => {
return new Promise((resolve, reject) => {
//...
if (success) {
resolve("Stuff worked!");
} else {
reject(Error("It broke"));
}
});
}
f('username', 'password')
to create the f
function that takes the username
and password
.
In it, we return a promise created by the Promise
constructor.
The callback that we pass into Promise
does something with username
and password
and call resolve
if success
is true
and reject
otherwise to reject the promise.
Then we call f
with the arguments we want.
Conclusion
To pass parameters to a promise function with JavaScript, we can create a function that takes the parameters we want to returns the promise.