Created
March 29, 2016 02:40
-
-
Save jamesdabbs/08848a5e052f9e6b9c61 to your computer and use it in GitHub Desktop.
Some promises
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
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