Created
June 14, 2020 10:57
-
-
Save kuczmama/1a0adbf2cf3a3df1a50120eb932f90ff to your computer and use it in GitHub Desktop.
Async Callbacks in javascript
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 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