Furthermore, a promise can actually end up being in two different states:
- resolved: in which case data is available
- rejected: in which case something went wrong and no value is available
Thankfully, the 'then' method accepts two parameters: one for when the promise was resolved, another for when the promise was rejected.
example:
- promise.then( function( futureValue ) {
- /* we got a value */
- } , function() {
- /* something went wrong */
- } );
In the case of certain applications, it is necessary to have several results returned before your application can continue at all (for example, displaying a dynamic set of options on a screen before a user is able to select the option that interests them).Where this is the case, a method called 'when' exists, which can be used to perform some action once all the promises have been fully fulfilled:
- when(
- promise1,
- promise2,
- ...
- ).then(function( futureValue1, futureValue2, ... ) {
- /* all promises have completed and are resolved */
- });
A good example is a scenario where you may have multiple concurrent animations that are being run. Without keeping track of each callback firing on completion, it can be difficult to truly establish once all your animations have finished running. Using promises and 'when' however this is very straight-forward as each of your animations can effectively say ‘we promise to let you know once we're done'. The compounded result of this means it's a trivial process to execute a single callback once the animations are done. For example:
- when(
- function(){
- /* animation 1 */
- /* return promise 1 */
- },
- function(){
- /* animation 2 */
- /* return promise 2 */
- }
- ).then(function(){
- /* once both animations have completed
- we can then run our additional logic */
- });
reference
No comments:
Post a Comment