Skip to content

Instantly share code, notes, and snippets.

@rewop
Created March 10, 2019 14:38
Show Gist options
  • Save rewop/bccbbdbea5f41303f917e905d095277a to your computer and use it in GitHub Desktop.
Save rewop/bccbbdbea5f41303f917e905d095277a to your computer and use it in GitHub Desktop.

This gist shows why we should avoid register to the window load event inside a promise chain. I encountered this bug at work, and this is the demostration of how to reproduce it.

Notice how the console.log at line 19 of script.js is never called, and the console never prints Do something on load.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
function daAThing() {
return new Promise((resolve) => {
console.log("Do something");
setTimeout(resolve);
});
}
function doAnotherThing() {
return new Promise((resolve) => {
console.log("Do another thing");
setTimeout(resolve);
});
}
function doSomethingOnLoad() {
return new Promise((resolve) => {
console.log("Setup something on load");
window.addEventListener('load', () => {
console.log("Do something on load");
resolve();
});
});
}
window.addEventListener('load', () => {
console.log('onLoad');
});
function doSomethingThatTakesLong() {
console.log('Do something long');
return new Promise((resolve) => {
setTimeout(resolve, 500);
});
}
doSomethingThatTakesLong()
.then(() => {
Promise.all([
daAThing(),
doAnotherThing(),
doSomethingOnLoad(),
])
})
.catch(err => {
console.error(err);
})
.then(() => {
console.log('All done');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment