Skip to content

Instantly share code, notes, and snippets.

@ungarson
Created July 7, 2019 11:38
Show Gist options
  • Save ungarson/d2f7739b533b63698924e1d11aca0572 to your computer and use it in GitHub Desktop.
Save ungarson/d2f7739b533b63698924e1d11aca0572 to your computer and use it in GitHub Desktop.
Async collector in javascript
export default class AsyncCollector {
gotData = [];
constructor(timeout, ...funcs) {
return new Promise((resolve, reject) => {
const promisesOfFuncs = funcs.map(item => item());
Promise.all(promisesOfFuncs)
.then(values => this.gotData = values)
.then(() => {
setTimeout(() => {
resolve(this.gotData);
}, timeout);
});
});
}
}
// Example of usage
// function getImg() {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve("image");
// }, 500);
// });
// }
// function getText() {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve("text");
// }, 900);
// });
// }
// (async () => {
// let dataFromServer = await new AsyncCollector(1000, getImg, getText);
// console.log(dataFromServer);
// })();
@ungarson
Copy link
Author

ungarson commented Jul 7, 2019

In what situations might it be useful? Imagine you need to get a data from server A and server B, and you want to combine these datas in an array. So here it is. Collector!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment