To gain a better grasp of ES6 Promises, I decided to tackle this particular challenge:
There are three divs: div.red
, div.green
, and div.blue
. They need to be displayed sequentially, each with a gradual increase in opacity through an async task using setInterval
.
The objective is to execute 3 async tasks in sequence.
Below is the code snippet I wrote. Unfortunately, it encounters an issue during the rejection stage and throws a TypeError: undefined is not a function {stack: (...), message: "undefined is not a function"}
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style type="text/css">
div{ width:100px; height:100px; opacity:0; }
.red{ background:red; }
.green{ background:green; }
.blue{ background:blue; }
</style>
</head>
<body>
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
<script type="text/javascript">
function appear(div){
console.log("appear");
console.log(div);
return new Promise(function(resolve, reject){
console.log("promise");
console.log(div.attr("class"));
var i = 0;
var loop = setInterval(function(){
if (i == 1){
clearInterval(loop);
console.log("animation end");
resolve(true);
}
div.css({"opacity": i});
i+=0.1;
},100);
});
}
$(document).ready(function(){
var divList = []
$("div").each(function(){
divList.push($(this));
});
console.log("start");
(function(){
return divList.reduce(function(current, next) {
return appear(current).then(function() {
return appear(next);
}, function(err) { console.log(err); }).then(function() {
console.log("div animation complete!")
}, function(err) { console.log(err); });
}, Promise.resolve()).then(function(result) {
console.log("all div animation done!");
}, function(err) { console.log(err); });
})();
});
</script>
</body>
</html>