簡體   English   中英

試圖了解ES6承諾:依次執行三個setIntervals

[英]Trying to understand ES6 Promises: executing three setIntervals sequentially

為了了解ES6 Promises的方式,我嘗試解決此問題聲明:

共有三個div: div.reddiv.greendiv.blue 它們必須一個接一個地出現,每一個都有一個setInterval迭代不透明度增量 (異步任務)。

因此,目標是依次執行3個異步任務。

我已經編寫了以下代碼,這進入了拒絕部分,並給出了TypeError :undefined不是函數{stack:(...),消息:“ undefined不是函數”}

<!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是表示鏈當前(最新)步驟而不是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);
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM