Last active
February 16, 2017 13:31
-
-
Save lubien/569222a11297e375072beba7dcc73574 to your computer and use it in GitHub Desktop.
Promise races
This file contains 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
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