zoukankan      html  css  js  c++  java
  • 使用Promise

    Promise所要解决的问题:回调地狱

    asyncTask1(data, function (data1){
    
        asyncTask2(data1, function (data2){
    
            asyncTask3(data2, function (data3){
                    // .... 魔鬼式的金字塔还在继续
            });
    
        });
    
    });
    

    Promise将原来回调地狱中的回调函数,从横向式增加巧妙的变为了纵向增长。以链式的风格,纵向的书写,使得代码更加的可读和易于维护。

    asyncTask1(data)
        .then(function(data1){
            return asyncTask2(data1);
        })
        .then(function(data2){
           return asyncTask3(data2);
        })
        // 仍然可以继续then方法
    

    Promise规范

    Promise规范如下:

    • 一个promise可能有三种状态:等待(pending)、已完成(fulfilled)、已拒绝(rejected)
    • 一个promise的状态只可能从“等待”转到“完成”态或者“拒绝”态,不能逆向转换,同时“完成”态和“拒绝”态不能相互转换
    • promise必须实现then方法(可以说,then就是promise的核心),而且then必须返回一个promise,同一个promise的then可以调用多次,并且回调的执行顺序跟它们被定义时的顺序一致
    • then方法接受两个参数,第一个参数是成功时的回调,在promise由“等待”态转换到“完成”态时调用,另一个是失败时的回调,在promise由“等待”态转换到“拒绝”态时调用。同时,then可以接受另一个promise传入,也接受一个“类then”的对象或方法,即thenable对象。

    小例子

    function wait(duration){
        return new Promise(function(resolve, reject) {
            setTimeout(resolve,duration);
        })
    }
    

    测试这个方法的代码如下:wait(5000).then(function(){alert('hello')}),这段代码很简单,就是等待5秒以后执行一个回调,弹出一个消息。当然,你还可以这样写:

    wait(5000).then(function(){alert('hello')}).then(function(){console.log('world')})
    使用Promise.all直到数组中的Promise对象全部执行完毕才执行then中的处理函数
    Promise.all([wait(3000), wait(4000)]).then(function(){console.log("haha")})
    

    Promise是一种写法,并非必不可少

    Promise更像是一种漂亮的形式,它能减少代码嵌套。
    在Java中,Promise形式的写法让Java变得不那么像汇编语言。

    class Person {
        int age;
        String name;
    
        Person setAge(int age) {
            this.age = age;
            return this;
        }
    
        Person setName(String name) {
            this.name = name;
            return this;
        }
    }
    //使用时
    Person p=new Person().setAge(20).setName("haha");
    //而传统写法
    Person p=new Person();
    p.setAge(20);
    p.setName("haha");
    

    参考资料

    Promise的前世今生和妙用技巧
    https://www.cnblogs.com/yunfeifei/p/4453690.html
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

  • 相关阅读:
    linux 免密登录
    mysql 重置从库
    elasticsearch原理及简介
    多线程编程--心得
    为什么我们做分布式使用Redis?
    JAVA-JVM调优
    JAVA-JVM调优标志
    Spirng-Mvc之Servlet篇
    Agent Job代理 执行SSIS Package
    Python之爬虫的理解
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/7833906.html
Copyright © 2011-2022 走看看