Skip to content

Instantly share code, notes, and snippets.

@jamesdabbs
Created March 29, 2016 02:40
Show Gist options
  • Save jamesdabbs/08848a5e052f9e6b9c61 to your computer and use it in GitHub Desktop.
Save jamesdabbs/08848a5e052f9e6b9c61 to your computer and use it in GitHub Desktop.
Some promises
function tickingPromise(seconds, value) {
return new Promise((resolve, reject) => {
let i = 0;
let timer = setInterval(() => {
i += 1
console.log("Tick", i)
if (i == seconds) {
resolve(value)
clearInterval(timer)
}
}, 500)
})
}
function impatientWaiter(seconds, value) {
console.log(`Resolving with ${value} in ${seconds}`)
return new Promise((resolve, reject) => {
if (seconds < 10) {
setTimeout(() => { resolve(value) }, seconds * 500)
} else {
reject(Error(`${seconds} seconds is _way_ too long`))
}
})
}
function probably(value, failureOnceIn=4) {
return new Promise((resolve, reject) => {
if (Math.random() > 1/failureOnceIn) {
const wait = 500 * (Math.random() + 0.5)
setTimeout(() => { resolve(value) }, wait)
} else {
reject(Error("Random failure"))
}
})
}
let keyListenerQueue = []
document.addEventListener("keypress", (event) => {
console.log("you pressed", event.which)
let fn
if (fn = keyListenerQueue.shift()) {
fn(event.which)
}
})
function getKeyPress() {
return new Promise((resolve, reject) => {
keyListenerQueue.push(resolve)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment