Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 899
user3110667 Avatar asked Oct 02 '15 17:10

user3110667


People also ask

How do you pass parameters to a promise?

To pass parameters to a promise function with JavaScript, we can create a function that takes the parameters we want to returns the promise. to create the f function that takes the username and password . In it, we return a promise created by the Promise constructor.

Can promise be chained?

Introduction to the JavaScript promise chainingThe callback passed to the then() method executes once the promise is resolved. In the callback, we show the result of the promise and return a new value multiplied by two ( result*2 ).

Does promise all run sequential?

all() method executed by taking promises as input in the single array and executing them sequentially.

Does promise all resolve promises in order?

Here, Promise. all() method is the order of the maintained promises. The first promise in the array will get resolved to the first element of the output array, the second promise will be a second element in the output array and so on.


1 Answers

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.

like image 138
jib Avatar answered Sep 28 '22 22:09

jib