Last active
July 10, 2023 21:36
-
-
Save jaz303/5e702c797819c388ac98 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function makeProgressPromise(cb) { | |
| var currentProgress = 0; | |
| var progressListeners = []; | |
| function updateProgress(newProgress) { | |
| currentProgress = newProgress; | |
| progressListeners.forEach(function(listener) { | |
| try { | |
| listener(currentProgress); | |
| } catch (e) { | |
| // swallow errors in listeners | |
| } | |
| }); | |
| } | |
| var p = new Promise(function(yes, no) { | |
| cb(yes, no, updateProgress); | |
| }); | |
| p.progress = function(cb) { | |
| progressListeners.push(cb); | |
| // update new listeners with current progress immediately | |
| cb(currentProgress); | |
| return this; | |
| } | |
| return p; | |
| } | |
| function ajax(method, url) { | |
| return makeProgressPromise(function(yes, no, progress) { | |
| // perform operation, call progress() with updates | |
| }); | |
| } | |
| // | |
| // Usage | |
| ajax('GET', '/orders.php') | |
| .progress(function(p) { /* update progress meter with value of `p` */ }) | |
| .then(function(result) { | |
| // ... | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment