|jQuery 3 - Implementing Promises|
|Written by Ian Elliot|
|Monday, 29 May 2017|
Page 3 of 3
Extending the Race Function
Of course, you could add the race function as a method to the promise object.
To implement the jQuery approach we simply use the arguments array:
and to call the function:
Notice that now there is a single array parameter.
Of the two, I think I prefer the arguments approach used by jQuery.
This is an implementation of the standard race function, but it is generally held that it isn't very useful as it will return the first function to complete, even if it rejects. What would be better is an implementation of any, which is found in some promise libraries, that returns the first successful result or a reject if there is no successful function:
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.
As 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:
Again, this is very simple. All that happens is that a new Deferred is created and is resolved if the original promise resolves and is rejected if the setTimeout is triggered first. This would be easier to use as a method added to the promise object because then it could be used with chaining.
Once you understand the way promises can be used to trigger other promises the only problem is that you will go too far with the idea. Keep it simple and only write the code you actually need. Promises are a reasonably good solution to the asynchronous problem, but the soon to be common async and await is so much better. Promises are a solution for now, but not for the longer term future.
Just jQuery The Core UI - Selectors
Selectors are what jQuery uses to pick out particular objects in the DOM. While this might start out simply enough, it can appear to be complicated in more testing examples. The trick is to always rem [ ... ]
Just jQuery The Core UI - The DOM
or email your comment to: email@example.com