Skip to content

Instantly share code, notes, and snippets.

@kuczmama
Created June 14, 2020 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuczmama/1a0adbf2cf3a3df1a50120eb932f90ff to your computer and use it in GitHub Desktop.
Save kuczmama/1a0adbf2cf3a3df1a50120eb932f90ff to your computer and use it in GitHub Desktop.
Async Callbacks in javascript
function fetchSports(prefix, callback) {
console.log("prefix", prefix);
const sports = ["vikings", "vipers"];
setTimeout(() => callback(sports), 500);
}
function fetchNews(prefix, callback) {
const news = ["victory", "votes"];
setTimeout(() => {
callback(news);
}, 1000);
}
const fetchAll = combine([fetchSports, fetchNews]);
fetchAll("v", (results) => console.log("My fetch all results", results));
function combine(fetchers) {
const promises = fetchers.map((fn) => promisify(fn));
return (prefix, callback) => {
Promise.all(promises.map((promise) => promise(prefix))).then((results) => {
callback([].concat(...results));
});
};
}
function promisify(fn) {
return (...args) => {
return new Promise((resolve) => {
const callback = (results) => {
resolve(results);
};
args.push(callback);
fn(...args);
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment