189

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"));
  }
});
6
  • 1
    There's no reason to do that, you can just define username and password in a higher scope
    – adeneo
    Feb 10, 2016 at 14:56
  • 3
    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?
    – kundante
    Feb 10, 2016 at 15:00
  • 1
    @kundante You don't need any globals. Learn about closures.
    – SLaks
    Feb 10, 2016 at 15:03
  • @adeneo the promise is async - what if he invokes the function a second time before the first promise is resolved ? Apr 5, 2019 at 10:08
  • 7
    @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.
    – hannodb
    Sep 23, 2020 at 11:21

8 Answers 8

370

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
});
5
  • 1
    what is someModule?
    – Si8
    Oct 9, 2018 at 18:06
  • 4
    It's just an example from the OP
    – Shanoor
    Oct 13, 2018 at 11:09
  • 3
    @Shanoor What is uid? Is it the string "Stuff worked!"?
    – Old Geezer
    Jul 16, 2019 at 16:34
  • 2
    @OldGeezer, it's just a variable to hold the return from the promise. In this case, yes, that would be "Stuff worked!".
    – Shanoor
    Jul 19, 2019 at 8:06
  • do you know how to call a function from the parent class within the new promise ? Jul 16, 2020 at 13:44
11

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

5
  • 2
    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]); Mar 12, 2018 at 8:36
  • 1
    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 May 11, 2019 at 14:38
  • 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.
    – sadiq
    May 12, 2019 at 4:03
  • 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 May 12, 2019 at 4:50
  • 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.
    – sadiq
    May 12, 2019 at 12:02
8

Even shorter

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

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

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...
    });
1
  • 1
    hi Jermine, it would be better to add some description to your answer.
    – Abilogos
    Jan 27, 2021 at 22:45
5

Not sure if understand correctly but in order to send argument from promise to another function you can do something like this:

function logUser(username, password){
    return new Promise((resolve, reject) => {
        let response = 'user logged in'
        resolve(response)
    })
}

function showMessage(msg){
    console.log(msg)
}

logUser('user', 'pass').then((respFromLogUser) => {
    showMessage(respFromLogUser)
})

4

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"}));
3
  • 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
    – DevAS
    Jul 14, 2019 at 23:20
  • @DevAS <button onclick="then_function(SaveImagesToFirebase.bind(this))"></button> script is ` var then_function=function(promise){new Promise(promise).then(function(e){/*code*/})}; function SaveImagesToFirebase(resolve,reject){/*code*/ resolve(/*???*/);}`
    – gogog
    Jul 16, 2019 at 12:11
  • 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);
    – Daweb
    Oct 29, 2020 at 10:12
2

I know this is old, but this may help someone digging through google. This is a more practical example where I just pass 2 parameters to a promise function and wait for it to resolve. Hopefully this helps. The setTimeout simulates "processing time". After 3 seconds the value will be returned from the promise and printed to screen.

const addNumbers = (a, b) => {
    
  return new Promise((resolve, reject) => {
    
    setTimeout(() => {
      resolve(a + b);
    }, 3000);
  
  });
  
  
};

let getResult = async (a, b) => {
    let value = await addNumbers(a, b);
    console.log(value);
};

getResult(1, 3);
0

i use this..

let verifyEmail = (email) => new Promise((resolve, rejected) => {
    let rsp = {isRepeated:false}
    let sql = `select id from users where email='${email}' `
    try{
        db.query(sql, (err,result)=>{
            if(!err){
                if(result.length > 0){
                    rsp = {isRepeated:true}
                }
            }
        })
        resolve(rsp)
    }catch(e){
        rejected({ok:false,err:e})
    }
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.