Skip to content

Instantly share code, notes, and snippets.

@cevek
Last active June 4, 2018 21:14
Show Gist options
  • Save cevek/168ef793108895c2a0bd783e6870f69d to your computer and use it in GitHub Desktop.
Save cevek/168ef793108895c2a0bd783e6870f69d to your computer and use it in GitHub Desktop.
Wait until all async is done
var arr = [];
function allDone() { console.log('All done') }
function replaceCallback(callback) {
if (typeof callback !== 'function') return callback;
arr.push(callback);
return function () {
var pos = arr.indexOf(callback);
if (pos > -1) arr.splice(pos, 1);
var res = callback.apply(this, arguments);
if (arr.length === 0) allDone();
return res;
}
}
function replaceAsync(fn, callbackPos) {
return function (...args) {
args[callbackPos] = replaceCallback(args[callbackPos]);
return fn.apply(this, args);
}
}
window.setTimeout = replaceAsync(setTimeout, 0);
// window.setImmediate = replaceAsync(setImmediate, 0);
window.requestAnimationFrame = replaceAsync(requestAnimationFrame, 0);
Promise.prototype.then = replaceAsync(Promise.prototype.then, 0);
// todo: second callback
Promise.prototype.catch = replaceAsync(Promise.prototype.catch, 0);
var onreadystatechange = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'onreadystatechange');
// todo check all callback, onerror, onload etc
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
get() {
return onreadystatechange.get.call(this);
},
set(cb) {
// todo: check that is fully loaded
onreadystatechange.set.call(this, replaceCallback(cb));
}
})
setTimeout(function () { console.log('setTimeout done'); }, 2000);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.github.com/users/octocat/orgs', true);
xhr.send();
xhr.onreadystatechange = function () {
console.log('xhr done');
}
fetch('https://api.github.com/users/octocat/orgs').then(res => res.json()).then(() => {
console.log('fetch done');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment