Promises, pass additional parameters to then chain

user3110667 picture user3110667 · Oct 2, 2015 · Viewed 95.5k times · Source

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?

Answer

jib picture jib · Oct 5, 2015

Perhaps the most straightforward answer is:

P.then(function(data) { return doWork('text', data); });

Or, since this is tagged ecmascript-6, using arrow functions:

P.then(data => doWork('text', data));

I find this most readable, and not too much to write.