Search code examples
javascriptpromiseecmascript-6es6-promise

Promises, pass additional parameters to then chain


A promise, just for example:

var P = new Promise(function (resolve, reject) {
  var a = 5;
  if (a) {
    setTimeout(function(){
      resolve(a);
    }, 3000);
  } else {
    reject(a);
  }
});

After we call the .then() method on the promise:

P.then(doWork('text'));

Then doWork function looks like this:

function doWork(data) {
  return function(text) {
    // sample function to console log
    consoleToLog(data);
    consoleToLog(b);
  }
}

How can I avoid returning an inner function in doWork, to get access to data from the promise and text parameters? Are there any tricks to avoiding the inner function?


Solution

  • You can use Function.prototype.bind to create a new function with a value passed to its first argument, like this

    P.then(doWork.bind(null, 'text'))
    

    and you can change doWork to,

    function doWork(text, data) {
      consoleToLog(data);
    }
    

    Now, text will be actually 'text' in doWork and data will be the value resolved by the Promise.

    Note: Please make sure that you attach a rejection handler to your promise chain.


    Working program: Live copy on Babel's REPL

    function doWork(text, data) {
      console.log(text + data + text);
    }
    
    new Promise(function (resolve, reject) {
        var a = 5;
        if (a) {
          setTimeout(function () {
            resolve(a);
          }, 3000);
        } else {
          reject(a);
        }
      })
      .then(doWork.bind(null, 'text'))
      .catch(console.error);