A Promise is a bundle of things you want to happen when a process comes to an end. But didn’t a motivational poster once tell you that the journey is as important as the destination? Did you learn nothing from that poster?
Fortunately, the jQuery team soaked up that wisdom (and the Promises/A specification) and, in jQuery 1.7, added a new kind of Promise callback that can be invoked any number of times. It’s called progress. For example, suppose we want to update an indicator of how far a person has gotten toward their daily word goal for National Novel Writing Month (NaNoWriMo).[34]
| var nanowrimoing = $.Deferred(); |
| var wordGoal = 5000; |
| nanowrimoing.progress(function(wordCount) { |
| var percentComplete = Math.floor(wordCount / wordGoal * 100); |
| $('#indicator').text(percentComplete + '% complete'); |
| }); |
| nanowrimoing.done(function(){ |
| $('#indicator').text('Good job!'); |
| }); |
With the nanowrimoing Deferred available, here’s how we respond to potential changes in word count:
| $('#document').on('keypress', function(){ |
| var wordCount = $(this).val().split(/s+/).length; |
| if (wordCount >= wordGoal) { |
| nanowrimoing.resolve(); |
| }; |
| nanowrimoing.notify(wordCount); |
| }); |
The notify call on the Deferred invokes our progress callback. Just like resolve and reject, notify can take arbitrary arguments. Note that calls to nanowrimoing.notify will have no effect once nanowrimoing is resolved, just like any additional resolve and reject calls would be ignored.
So, to recap, a Promise takes three kinds of callbacks: done, fail, and progress. done callbacks run when the Promise resolves, fail callbacks run when it’s rejected, and progress callbacks run whenever notify is called on a pending Deferred.
18.119.133.241