体验 Promise 优美的链式写法

古人云:“君子一诺千金”,这种“承诺将来会执行”的对象在 JavaScript 中称为 Promise 对象。Promise 有各种开源实现,在 ES6 中被统一规范,由浏览器直接支持。

浏览器中的 Promise 对象

在下面的代码中通过使用 callback 和 Promise 来体验

  • callback 臭名昭著的邪恶金字塔
  • Promise 优美的链式写法
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>体验 Promise 的链式写法</title>
    <style>
        .ball {
            width: 40px;
            height: 40px;
            border-radius: 20px;
        }

        .ball1, .ball4 {
            background: red;
        }

        .ball2, .ball5 {
            background: green;
        }

        .ball3, .ball6 {
            background: yellow;
        }
    </style>
</head>
<body>
<h1>采用回调函数的方式来实现</h1>

<div class="ball ball1" style="margin-left: 0px;"></div>
<div class="ball ball2" style="margin-left: 0px;"></div>
<div class="ball ball3" style="margin-left: 0px;"></div>
<hr>
<h1>采用 Promise 的方式来实现</h1>

<div class="ball ball4" style="margin-left: 0px;"></div>
<div class="ball ball5" style="margin-left: 0px;"></div>
<div class="ball ball6" style="margin-left: 0px;"></div>

<script>
    var ball1 = document.querySelector('.ball1');
    var ball2 = document.querySelector('.ball2');
    var ball3 = document.querySelector('.ball3');
    var ball4 = document.querySelector('.ball4');
    var ball5 = document.querySelector('.ball5');
    var ball6 = document.querySelector('.ball6');

    //    /**
    //     * 方法一:采用 setTimeout 实现
    //     * @param ball
    //     * @param distance
    //     * @param callback
    //     */
    //    function animate(ball, distance, callback) {
    //        setTimeout(function () {
    //            var marginLeft = parseInt(ball.style.marginLeft);
    //            if (marginLeft == distance) {
    //                callback && callback();
    //                return; // 注意在这里一定要返回定时器对象,确保后面拿到的是一个新的定时器对象
    //            } else {
    //                if (marginLeft < distance) {
    //                    marginLeft++;
    //                } else {
    //                    marginLeft--;
    //                }
    //            }
    //            ball.style.marginLeft = marginLeft + 'px';
    //            animate(ball, distance, callback);
    //        }, 10);
    //    }

    /**
     * 方法二:采用 setInterval 实现
     * @param ball
     * @param distance
     * @param callback
     */
    function animate(ball, distance, callback) {
        var interval = setInterval(function () {
            var marginLeft = parseInt(ball.style.marginLeft);
            if (marginLeft == distance) {
                callback && callback();
                clearInterval(interval);
            } else {
                if (marginLeft < distance) {
                    marginLeft++;
                } else {
                    marginLeft--;
                }
            }
            ball.style.marginLeft = marginLeft + 'px';
        }, 10);
    }

    animate(ball1, 100, function () {
        animate(ball2, 200, function () {
            animate(ball3, 300, function () {
                animate(ball3, 150, function () {
                    animate(ball2, 150, function () {
                        animate(ball1, 150, function () {
                            //
                        });
                    });
                });
            });
        });
    });

    //    /**
    //     * 采用 Promise 实现
    //     * @param ball
    //     * @param distance
    //     * @returns {Promise}
    //     */
    //    function promiseAnimate(ball, distance) {
    //        return new Promise(function (resolve, reject) {
    //            var interval = setInterval(function () {
    //                var marginLeft = parseInt(ball.style.marginLeft);
    //                if (marginLeft == distance) {
    //                    resolve();
    //                    clearInterval(interval);
    //                } else {
    //                    if (marginLeft < distance) {
    //                        marginLeft++;
    //                    } else {
    //                        marginLeft--;
    //                    }
    //                }
    //                ball.style.marginLeft = marginLeft + 'px';
    //            }, 10);
    //        });
    //    }
    //
    //    promiseAnimate(ball4, 100)
    //            .then(function () {
    //                return promiseAnimate(ball5, 200);
    //            })
    //            .then(function () {
    //                return promiseAnimate(ball6, 300);
    //            })
    //            .then(function () {
    //                return promiseAnimate(ball6, 150);
    //            })
    //            .then(function () {
    //                return promiseAnimate(ball5, 150);
    //            })
    //            .then(function () {
    //                return promiseAnimate(ball4, 150);
    //            });

    /**
     * 采用 Promise 实现
     * @param ball
     * @param distance
     * @returns {Function}
     */
    function promiseAnimate(ball, distance) {
        return function () {
            return new Promise(function (resolve, reject) {
                var interval = setInterval(function () {
                    var marginLeft = parseInt(ball.style.marginLeft);
                    if (marginLeft == distance) {
                        resolve();
                        clearInterval(interval);
                    } else {
                        if (marginLeft < distance) {
                            marginLeft++;
                        } else {
                            marginLeft--;
                        }
                    }
                    ball.style.marginLeft = marginLeft + 'px';
                }, 10);
            });
        }
    }

    promiseAnimate(ball4, 100)()
            .then(promiseAnimate(ball5, 200))
            .then(promiseAnimate(ball6, 300))
            .then(promiseAnimate(ball6, 150))
            .then(promiseAnimate(ball5, 150))
            .then(promiseAnimate(ball4, 150))
</script>
</body>
</html>

效果图:


运动的最终结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354

推荐阅读更多精彩内容

  • 编后吐槽:写的快花眼,很详细,耐心看必受益匪浅 JavaScript的执行环境是「单线程」的。所谓单线程,是指JS...
    果汁凉茶丶阅读 4,629评论 8 27
  • 一.为什么需要promise? 开发网站的过程中,我们经常遇到某些耗时很长的javascript操作。其中,既有异...
    overflow_hidden阅读 12,426评论 2 21
  • 本文适用的读者 本文写给有一定Promise使用经验的人,如果你还没有使用过Promise,这篇文章可能不适合你,...
    HZ充电大喵阅读 7,305评论 6 19
  • Promise的含义:   Promise是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和...
    呼呼哥阅读 2,170评论 0 16
  • 这篇文章,是深圳海上世界之行回顾的正片。我把这篇文章单独抽出来,是源于自己大学社团经历的回忆。大雨中搬帐篷搭帐篷再...
    Mr_yuan1994阅读 287评论 0 0