为了理解 ES6 Promises 如何解决这个问题:
共有三个 div:div.red
、div.green
和 div.blue
。它们必须一个接一个地出现,每个都通过 setInterval
迭代不透明度增量(异步任务)。
所以目标是顺序执行 3 个异步任务。
我编写了以下代码,这会进入拒绝部分并给出TypeError:未定义不是函数{stack:(...),消息:“未定义是不是一个函数”}
<!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>
最佳答案
由于某种原因,您调用了appear(current)
。但是,current
是代表链的当前(最新)步骤的 Promise,而不是 div。它最初会传递 Promise.resolve()
,它不是 jQuery 对象,并且没有 .attr()
方法。
相反,使用
$(document).ready(function() {
console.log("start");
$("div").toArray().reduce(function(currentPromise, nextDiv) {
return currentPromise.then(function() {
return appear($(nextDiv));
});
}, Promise.resolve()).then(function() {
console.log("all div animation complete!")
}, function(err) {
console.log(err);
});
});
关于javascript - 尝试理解 ES6 Promise : executing three setIntervals sequentially,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26871959/