Search code examples
javascriptnode.jses6-promise

Promise: how to pass function with parameters?


In the following test code, I try to pass predefined function with parameters (i.e., t2, t3) to then. But it complains "r" not defined.

var Promise = require('bluebird');

var t2 = function(r) {
    console.log("2r: " + r);
    return 2 * r;
};

var t3 = function(r) {
    console.log("3r: " + r);
    return 3 * r;
};

new Promise(function(resolve, reject) {

    setTimeout(function() {
        resolve(1);
        reject(2)
    }, 1000);
})
.then(t2(r), t3(r))
.then(t2(r), t3(r))
.then(t2(r), t3(r));

Solution

  • Just pass the function names instead:

    var t2 = function(r) {
      console.log("2r: " + r);
      return 2 * r;
    };
    
    var t3 = function(r) {
      console.log("3r: " + r);
      return 3 * r;
    };
    
    new Promise(function(resolve, reject) {
    
        setTimeout(function() {
          resolve(1);
          reject(2)
        }, 1000); // (*)
    
      })
      .then(t2, t3)
      .then(t2, t3)
      .then(t2, t3);

    If you actually want to pass additional parameters that you know beforehand, make t2 and t3 higher-order functions that return functions, so that you can invoke inside a .then's parameter list:

    var t2 = extra => r => {
      console.log("2r: " + r);
      console.log('extra param: ' + extra);
      return 2 * r;
    };
    
    var t3 = extra => r => {
      console.log("3r: " + r);
      console.log('extra param: ' + extra);
      return 3 * r;
    };
    
    
    const r = 'foo';
    new Promise(function(resolve, reject) {
    
        setTimeout(function() {
          resolve(1);
          reject(2)
        }, 1000); // (*)
    
      })
      .then(t2(r), t3(r))
      .then(t2(r), t3(r))
      .then(t2(r), t3(r));