Created
March 27, 2013 22:16
-
-
Save Gozala/5258591 to your computer and use it in GitHub Desktop.
Caveats with sync promises
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
// Function returns promise for once window.document.readyState | |
// becomes interactivate. | |
function whenInteractive(window) { | |
let { promise, resolve } = defer() | |
let state = window.document.readyState; | |
if (state === "complete") resolve(window) | |
if (state === "interactive") resolve(window) | |
else { | |
window.addEventListener("DOMContentLoaded", function(event) { | |
// Is current window? | |
if (event.target === window.document) resolve(window) | |
}) | |
} | |
} | |
// When window becomes interactive we're supposed to do some stuff | |
// but if `resolve(window)` does call doStuff in next tick window | |
// may get closed by then without us having chance to do anything. | |
whenInteractive(window).then(doStuff) | |
// Simple utility to handle button press | |
function whenEnterPressed(button) { | |
let { promise, resolve } = defer() | |
button.addEventListener("click", function(e) { | |
resolve(e) | |
}) | |
return promise | |
} | |
whenEnterPressed(goFullScreenButton).then(function() { | |
// When full screen button is pressed we try to go fullscreen. | |
myVideo.mozRequestFullScreen() | |
// Unfortunately if callback is called in next tick we'll end | |
// with an exception: | |
// Request for full-screen was denied because Element.mozRequestFullScreen() | |
// was not called from inside a short running user-generated event handler. | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment