zoukankan      html  css  js  c++  java
  • 对Promise的质疑

    Promise是为了解决多层回调函数嵌套结构太深,代码逻辑不符合线性流程的问题。线性流程问题是解决了的,但是嵌套结构太深(每多一层回调就多一层缩进)感觉并没有解决。

    在不提取函数的情况下,串行异步加载3张图片的传统代码如下:

    var img1 = new Image();
    img1.onload=function (){
        var img2 = new Image();
        img2.onload=function (){
            var img3 = new Image();
            img3.onload=function (){
                console.log("ended");
            };
            img3.src="http://img1.bdstatic.com/static/home/widget/search_box_home/logo/home_white_logo_0ddf152.png";
        };
        img2.src="http://www.baidu.com/img/bd_logo.png";
    };
    img1.src="http://www.baidu.com/img/bd_logo1.png";

    用Promise之后的代码如下:

    new Promise(function (resolve, reject) {
        var img1 = new Image();
        img1.onload=function (){
            resolve();
        };
        img1.src="http://www.baidu.com/img/bd_logo1.png";
    }).then(function (){
        new Promise(function (resolve, reject) {
            var img2 = new Image();
            img2.onload=function (){
                resolve();
            };
            img2.src="http://www.baidu.com/img/bd_logo.png";
        }).then(function (){
            new Promise(function (resolve, reject) {
                var img3 = new Image();
                img3.onload=function (){
                    resolve();
                };
                img3.src="http://img1.bdstatic.com/static/home/widget/search_box_home/logo/home_white_logo_0ddf152.png";
            }).then(function (){
                console.log("ended");
            });
        });
    });

    可以看到代码顺序是得到纠正了,但是加载第3张图片的代码仍然有3个缩进。
    如果还是用传统的方法,但是提取函数的话,也可以让代码的逻辑稍微调整得更易读些,缩进问题也解决了,代码如下:

    function step1(){
        var img1 = new Image();
        img1.onload=function (){
            step2();
        };
        img1.src="http://www.baidu.com/img/bd_logo1.png";
    }
    function step2(){
        var img2 = new Image();
        img2.onload=function (){
            step3();
        };
        img2.src="http://www.baidu.com/img/bd_logo.png";
    }
    function step3(){
        var img3 = new Image();
        img3.onload=function (){
            console.log("ended");
        };
        img3.src="http://img1.bdstatic.com/static/home/widget/search_box_home/logo/home_white_logo_0ddf152.png";
    }
    step1();

    刚接触Promise,对它了解不多,不知道是不是还有更好的写法。

  • 相关阅读:
    Could not find package vendor/name in a version matching v-Number 是坑!
    Magento 2 Error: A technical problem with the server created an error. Try again to continue what you were doing. If the problem persists, try again later.
    七牛Qshell 常用命令打印
    VBA
    XUGUO-书呆子-搜索书箱
    Magento2 API 服务合同设计模式 依赖注入 介绍
    Magento2 Service contracts 服务合同
    Magento2自定义命令
    在Magento 2中创建管理员菜单
    Routing 为 Magento 2 一个重要的部分,本文介绍基本应用
  • 原文地址:https://www.cnblogs.com/omega8/p/5201847.html
Copyright © 2011-2022 走看看