Categories
JavaScript Answers

How to pass parameter to a promise function with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *