Skip to content

Instantly share code, notes, and snippets.

@jimjeffers
Last active July 13, 2017 18:31
Show Gist options
  • Save jimjeffers/1b6a91086fe9557cd39e79d703e81ece to your computer and use it in GitHub Desktop.
Save jimjeffers/1b6a91086fe9557cd39e79d703e81ece to your computer and use it in GitHub Desktop.
Generator + Promises === Shared Async Completion
/**
All of the intervals which call the pollDate() function
after different time intervals will resolve with similar
qualifying times thanks to managed state in the *fetchDate()
generator function.
*/
function* fetchDate() {
var isFetching = false
var date = 0
while (true) {
const diff = new Date().getTime() - date
if (!isFetching && diff > 500) {
isFetching = true
setTimeout(() => {
isFetching = false
date = new Date().getTime()
}, 250)
}
yield isFetching ? -1 : date
}
}
var gen = fetchDate()
function getDate(name) {
return new Promise((resolve, reject) => {
const date = gen.next().value
if (date > 0) {
resolve(date)
} else {
setTimeout(() => resolve(gen.next().value), 100)
}
})
}
const pollDate = async function(name) {
const date = await getDate(name)
return date > 0 ? date : pollDate(name)
}
const intervals = [0, 500, 501, 750, 1000, 2500]
intervals.map(interval =>
setTimeout(async () => {
const date = await pollDate(`After ${interval}`)
console.log(`"After ${interval}" Task Finished: ${date}`)
}, interval)
)
/**
Example console output:
> "After 0" Task Finished: 1499970482871
> "After 500" Task Finished: 1499970482871
> "After 501" Task Finished: 1499970482871
> "After 750" Task Finished: 1499970482871
> "After 1000" Task Finished: 1499970483735
> "After 2500" Task Finished: 1499970485236
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment