Skip to content

Instantly share code, notes, and snippets.

@jaz303
Last active July 10, 2023 21:36
Show Gist options
  • Select an option

  • Save jaz303/5e702c797819c388ac98 to your computer and use it in GitHub Desktop.

Select an option

Save jaz303/5e702c797819c388ac98 to your computer and use it in GitHub Desktop.
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