Promises, pass additional parameters to then chain

JavascriptPromiseEcmascript 6Es6 Promise

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

Use currying.

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

var curriedDoWork = function(text) {
    return function(data) {
        console.log(data + text);
    }
};

P.then(curriedDoWork('text'))
.catch(
    //some error handling
);

Solution 4 - Javascript

The new answer to this question is to use arrow functions (which automatically bind the this and are much more readable). Google for links such as: https://2ality.com/2016/02/arrow-functions-vs-bind.html

You can set the text like:

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

Note: this.text inside doWork will evaluate to 'text'.

This is suggested by jib above and that (or this!) should be the accepted answer now.

Solution 5 - Javascript

Lodash offers a nice alternative for this exact thing.

 P.then(_.bind(doWork, 'myArgString', _));
 
 //Say the promise was fulfilled with the string 'promiseResults'

 function doWork(text, data) {
     console.log(text + " foo " + data);
     //myArgString foo promiseResults
 }

Or, if you'd like your success function to have only one parameter (the fulfilled promise results), you can utilize it this way:

P.then(_.bind(doWork, {text: 'myArgString'}));

function doWork(data) {
    console.log(data + " foo " + this.text);
    //promiseResults foo myArgString
}

This will attach text: 'myArgString' to the this context within the function.

Solution 6 - Javascript

use this so you can access global variable inside the promise body

var ref=this;

Example

p.then((data)=>{
  var ref=this;
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3110667View Question on Stackoverflow
Solution 1 - JavascriptjibView Answer on Stackoverflow
Solution 2 - JavascriptthefourtheyeView Answer on Stackoverflow
Solution 3 - JavascriptyksView Answer on Stackoverflow
Solution 4 - JavascriptgiwyniView Answer on Stackoverflow
Solution 5 - JavascriptJellyRaptorView Answer on Stackoverflow
Solution 6 - Javascriptaryan singhView Answer on Stackoverflow