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.
Perhaps the most straightforward answer is:
Or, since this is tagged
ecmascript-6
, using arrow functions:I find this most readable, and not too much to write.
You can use
Function.prototype.bind
to create a new function with a value passed to its first argument, like thisand you can change
doWork
to,Now,
text
will be actually'text'
indoWork
anddata
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
Use currying.
Lodash offers a nice alternative for this exact thing.
Or, if you'd like your success function to have only one parameter (the fulfilled promise results), you can utilize it this way:
This will attach
text: 'myArgString'
to thethis
context within the function.