Promises, pass additional parameters to then chain

2019-01-07 05:30发布

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 then method on promise:

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

doWork function looks like this:

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

how can i avoid inner function in doWork, to get access to data from promise and text parameter? if there any tricks? thanks.

4条回答
我只想做你的唯一
2楼-- · 2019-01-07 05:39

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.

查看更多
Animai°情兽
3楼-- · 2019-01-07 05:42

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);
查看更多
不美不萌又怎样
4楼-- · 2019-01-07 05:52

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
);
查看更多
倾城 Initia
5楼-- · 2019-01-07 06:05

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.

查看更多
登录 后发表回答