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?
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.
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 ).
all() method executed by taking promises as input in the single array and executing them sequentially.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With