close

How to pass parameter to a promise function

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to pass parameter to a promise function in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to pass parameter to a promise function ?

  1. How to pass parameter to a promise function ?

    to pass parameter to a promise function Even shorter
    var foo = (user, pass) => new Promise((resolve, reject) => { if (/* condition */) { resolve("Fine"); } else { reject("Error message"); } }); foo(user, pass).then(result => { /* process */ });

  2. How to pass parameter to a promise function ?

    to pass parameter to a promise function Even shorter
    var foo = (user, pass) => new Promise((resolve, reject) => { if (/* condition */) { resolve("Fine"); } else { reject("Error message"); } }); foo(user, pass).then(result => { /* process */ });

Method 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
});

Method 2

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment