How to pass parameter to a promise function

162,153

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

Solution 2

Another way(Must Try):

var promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});
var extraData = 'ImExtraData';
promise1.then(function(value) {
  console.log(value, extraData);
  // expected output: "Success!" "ImExtraData"
}, extraData);

Solution 3

Even shorter

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

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

Solution 4

You can return your promise in a function with arguments. Like this:

function someFunction(username, password) {
    return new Promise((resolve, reject) => {
        // Do something with the params username and password...
        if ( /* everything turned out fine */ ) {
            resolve("Stuff worked!");
        } else {
            reject(Error("It didn't work!"));
        }
    });
}
    
someFunction(username, password)
    .then((result) => {
        // Do something...
    })
    .catch((err) => {
        // Handle the error...
    });

Solution 5

You can use .bind() to pass the param(this) to the function.

var someFunction =function(resolve, reject) {
  /* get username, password*/
  var username=this.username;
  var password=this.password;
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));
Share:
162,153

Related videos on Youtube

kundante
Author by

kundante

Full time developer, part time human...

Updated on May 10, 2022

Comments

  • kundante
    kundante almost 2 years

    this might seem a silly question but I am a newbie in this topic. I am working on promises on node js. And I want to pass parameter to a promise function. However I could not figure it out.

    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"));
      }
    });
    
    • adeneo
      adeneo about 8 years
      There's no reason to do that, you can just define username and password in a higher scope
    • kundante
      kundante about 8 years
      But I am calling the promise from another module, and also username and password are not static but coming from client-side. Is it safe to define somekind of gloabal variable that one function sets and the other one uses. Is there a risk that the variable is changed by another client?
    • SLaks
      SLaks about 8 years
      @kundante You don't need any globals. Learn about closures.
    • Mawg says reinstate Monica
      Mawg says reinstate Monica about 5 years
      @adeneo the promise is async - what if he invokes the function a second time before the first promise is resolved ?
    • hannodb
      hannodb over 3 years
      @adeneo - Please don't answer questions with "There is no reason to do that". You don't know that, and it's a really annoying response. The person might have specific reasons why he wants to do something a specific way which he didn't necessarily felt relevant to explain. Either it can be done, or it can't, and if it is a bad idea you can list the reasons. Clearly, as the answer with 248 upvotes below demonstrate, it can be done, and there is lots of reason to do it.
    • adeneo
      adeneo over 3 years
      @hannodb - Sure, but in this case the answer is to actually declare the variables in a higher scope, either as arguments, or declared directly, it's the only simple viable solution as Promise.then only has two arguments, none of them being user selectable. The accepted answer also declares the variables in a higher scope, which should tell you it was exactly what the OP wanted.
  • user5389726598465
    user5389726598465 about 6 years
    Your example would be better if you resolve with an array or object that you deconstruct so multiple arguments are shown and the verbose promise is created already resolved like so: Promise.resolve([arg1, arg2, arg3]);
  • Si8
    Si8 over 5 years
    what is someModule?
  • Shanoor
    Shanoor over 5 years
    It's just an example from the OP
  • Shakiba Moshiri
    Shakiba Moshiri almost 5 years
    I think it is wrong since the second parameter which is passed to then is a callback for handling the return value of reject function. Instead of resolve('Success!'); try reject('Error'); We will get error: Unhandled promise rejection Here we see the output because var extraData = 'ImExtraData'; is a global variable and NOT because of passing it using then
  • sadiq
    sadiq almost 5 years
    If you do not pass it you can't access it as it has not scope in promise/then if you do not pass it.
  • Shakiba Moshiri
    Shakiba Moshiri almost 5 years
    try to remove it and see if it works or not? codepen.io/k-five/pen/ZNOvKG see the console log in the your browser
  • sadiq
    sadiq almost 5 years
    I appreciate your codepen, but use two different variables and then see the real factor! AVOID the SAME VARIABLE. If just the global variable worked fine we did not need to pass extra parameter.
  • DevAS
    DevAS almost 5 years
    i have this function how to edit it to accept .then() when i invoke it in a Button ` SaveImagesToFirebase = () => { const uid = firebase.auth().currentUser.uid; // Provider const { images } = this.state; images.map(image => { let file = image.uri; console.log(file); const path = "Img" + Math.floor(Math.random() * 1500); console.log("@IMAGE", path); const ref = firebase .storage() .ref(provider/${uid}/ProviderGalary/${path}); ref.put(file); }); };` @gogog
  • gogog
    gogog almost 5 years
    @DevAS <button onclick="then_function(SaveImagesToFirebase.bind(this))"></b‌​utton> script is ` var then_function=function(promise){new Promise(promise).then(function(e){/*code*/})}; function SaveImagesToFirebase(resolve,reject){/*code*/ resolve(/*???*/);}`
  • Old Geezer
    Old Geezer almost 5 years
    @Shanoor What is uid? Is it the string "Stuff worked!"?
  • Shanoor
    Shanoor almost 5 years
    @OldGeezer, it's just a variable to hold the return from the promise. In this case, yes, that would be "Stuff worked!".
  • TimeParadox
    TimeParadox almost 4 years
    do you know how to call a function from the parent class within the new promise ?
  • Daweb
    Daweb over 3 years
    Exactly what I was looking for : to separate my functions so you don't need to wrap a anonymous function in your promise function f2(resolve, reject){ console.log('executing with params : ', this); setTimeout(() => resolve("done!"), this.delay) }; async function f1(data) { // process data here console.log('before'); let promise = new Promise(f2.bind(data)); let result = await promise; // wait until the promise resolves console.log('after'); // process result here alert(result); // "done!" } const data = {delay: 1000}; f1(data);
  • Abilogos
    Abilogos about 3 years
    hi Jermine, it would be better to add some description to your answer.