0

为了理解 ES6 Promises 我试图解决这个问题陈述:

有 3 个 div:div.reddiv.greendiv.blue。它们必须一个接一个地出现,每个都通过一个setInterval迭代的不透明度增量(异步任务)。

所以目标是顺序执行 3 个异步任务。

我已经编写了以下代码,这进入了拒绝部分并给出了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>
4

1 回答 1

1

出于某种原因,您调用appear(current). 但是,currentpromise 是代表链的当前(最新)步骤,而不是 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);
    });
});
于 2014-11-11T20:27:45.937 回答