JavaScript Async - Returning Promises |
Written by Ian Elliot | |||
Monday, 15 November 2021 | |||
Page 2 of 2
The second is to use a technique from functional programming called "currying" to reduce the number of parameters in the function. For example: getTime(); delay(1000) .then(getTime) .then(function(){return delay(1000,0);}) .then(getTime); In this case we have used the anonymous function to curry the delay function, i.e. we have reduced the number of parameters to zero. If you try this you will find that it works and each of the times is roughly 1000ms apart. You can take this one-off currying and create a function that will automatically curry delay for you, for example: function delay(t,p) { return function () { var promise = new Promise( You can see that this is the same idea, but now the delay function returns a function that delays for t milliseconds with no parameters. With this version of delay you can use: getTime(); delay(1000)() .then(getTime) .then(delay(1000)) .then(getTime); The extra parentheses following the first use of delay are not a misprint. The delay function returns a function that delays for t milliseconds and to implement the delay it has to be called. The need for the double pairs of parentheses is not nice, but there seems to be no way that a function that returns a Promise and accepts parameters can be used in the same way outside and inside a then. The final way of doing the job is to use bind to curry the delay function. The bind function returns another function with a specified context and fixed values for any of its parameters. Using the original delay function we can call it in a then using: getTime(); delay(1000) .then(getTime) .then( delay.bind(null,1000,0)) .then(getTime); The bind returns a function with the call context set to null and the first parameter set to 1000 and the second to 0. The call to bind is reputed to be slow. Of the solutions, probably the best is to write the function using a parameter and remember to wrap it in an anonymous currying function if you use it in a then: .then(function(){return delay(1000);}) This is one of the negative features of using Promises. You have to remember that a function that returns a Promise can have parameters, but you cannot specify these parameters when you use the function in a then unless you use currying or something similar. Included In Chapter But Not In This Extract
Summary
Now Available as a Book:JavaScript AsyncYou can buy it from: Amazon Contents
Also by Ian ElliotJust JavaScript: An Idiomatic Approach To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info <ASIN:1871962560> <ASIN:1871962579> <ASIN:1871962528> <ASIN:1871962501>
|
|||
Last Updated ( Monday, 15 November 2021 ) |