Sometimes, we want to pass parameter to a promise function with JavaScript.
In this article, we’ll look at how to pass parameter to a promise function with JavaScript.
How to pass parameter to a promise function with JavaScript?
To pass parameter to a promise function with JavaScript, we create a function that takes the parameter and returns the promise.
For instance, we write
const logUser = (username, password) => {
return new Promise((resolve, reject) => {
//...
const response = "user logged in";
resolve(response);
});
};
logUser("user", "pass").then((respFromLogUser) => {
showMessage(respFromLogUser);
});
to create the logUser
function that returns a promise that uses the username
and password
parameters.
Then we call logInUser
with the arguments and call then
with a callback that has the resolved value set as the value of the callback parameter.
Conclusion
To pass parameter to a promise function with JavaScript, we create a function that takes the parameter and returns the promise.