JavaScript Async - Composing Promises |
Written by Ian Elliot | |||
Monday, 13 July 2020 | |||
Page 2 of 2
AnyWhat would be better is an implementation of any, which is found in some Promise libraries and soon to be included in ECMAScript. Any returns the first successful result, or a reject if there is no successful function at all: function any(args) { This works in a very similar way to race, but we now maintain a count of the number of Promises included in the arguments. Each time a Promise is rejected we reduce the count by one. If the count reaches zero then all of the Promises have been rejected and we change the state of the returned Promise to rejected. Notice that as long as one of the Promises resolves, the returned Promise resolves. As before, we make no attempt to cancel any no longer wanted Promises or tasks. TimeoutAs a final example, and one that is useful in practice, let's explore a timeOut function. One of the problems with Promises is that they don't have a timeout. If a Promise isn't resolved or rejected then it will continue to be pending forever. The following function takes a Promise and returns a new Promise that will reject if the original Promise doesn't accept or reject within the specified timeout: function timeOut(p, t) { var promise = new Promise( function (resolve, reject) { p.then(function (value) { resolve(value); }, Again, this is very simple. All that happens is that a new Promise is created and is resolved if the original Promise resolves, or rejected if the setTimeout is triggered first. For example: myPromise = delay(2000, 0); timeOut(myPromise, 1000).then( function () { console.log("success"); }, function () { console.log("failure"); }); In this case the Promise times out and fails. If you change the delay to less than 1000 milliseconds then the Promise succeeds. This would be easier to use as a method added to the Promise object because then it could be used with chaining. 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 ( Saturday, 12 September 2020 ) |