I have an image event handling code below as
HTML
<!DOCTYPE html>
<html>
<head>
<title>Promise DEMO</title>
</head>
<body>
<img src="someImagePath.jpg" class="img-1"/>
</body>
</html>
JavaScript
var img1 = document.querySelector('.img-1');
img1.addEventListener('load', function() {
// woo yey image loaded
});
img1.addEventListener('error', function() {
// argh everything's broken
});
What would be the case, where it will be possible that the events happen before I start listening to them?
Aim is to understand why I should use promises.
Generally speaking, events (including DOM changes) in javascript are completely async, thus the point in time when you bind a listener to an object can happen before or after the event is happening.
Simple example:
A more detailed explanation about these scenarios and how using promises can solve them can be found at the link below:
http://www.html5rocks.com/en/tutorials/es6/promises/