Created
July 7, 2019 11:38
-
-
Save ungarson/d2f7739b533b63698924e1d11aca0572 to your computer and use it in GitHub Desktop.
Async collector 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
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); | |
// })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!