Skip to content

Instantly share code, notes, and snippets.

@lubien
Last active February 16, 2017 13:31
Show Gist options
  • Save lubien/569222a11297e375072beba7dcc73574 to your computer and use it in GitHub Desktop.
Save lubien/569222a11297e375072beba7dcc73574 to your computer and use it in GitHub Desktop.
Promise races
const $page = document.getElementById('page')
const router = {
listeners: [],
onPageChange(fn) {
this.listeners.push(fn)
}
}
const setPage = title => {
$page.innerText = title
}
const loadPage = (title, time) =>
new Promise(resolve =>
setTimeout(() => resolve(title), time)
)
const switcher = () => {
let on = true
return {
on() { on = true },
off() { on = false },
wire(val) {
if (on) return val
throw new Error('Cancelled')
}
}
}
const pageUnchanged = () => {
const pageSwitch = switcher()
router.onPageChange(pageSwitch.off)
return pageSwitch.wire
}
const onClickChangePage = button =>
button.addEventListener('click', () => {
const nextPage = button.getAttribute('data-page')
const delay = +button.getAttribute('data-delay')
router.listeners.forEach(fn => fn())
loadPage(nextPage, delay)
.then(pageUnchanged())
.then(setPage)
})
Array.from(document.getElementsByTagName('button'))
.map(onClickChangePage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment