zoukankan      html  css  js  c++  java
  • ES6 Promises

    Promises通过一种简单干净的方法实现JavaScript的异步编程,它是ES6的新功能。先看下面几个例子(可以使用node测试):

    SyncCallback(同步回调):

    function notifyAll(a, b)
    {
        console.log("starting notification process");
        
        a();
        b();
    }
    
    function notify1()
    {
        console.log("Hey, one.");
    }
    
    function notify2()
    {
        console.log("Hey, two.");
    }
    
    notifyAll(notify1, notify2);
    

      

     AsyncCallback(异步回调,基于setTimeout):

    function notifyAll(a, b)
    {
        setTimeout(function(){
            console.log("starting notification process");
            a();
            b();
        }, 2000);
    }
    
    function notify1()
    {
        console.log("Hey, one.");
    }
    
    function notify2()
    {
        console.log("Hey, two.");
    }
    
    notifyAll(notify1, notify2);
    

      

     再看一个基于setTimeout极端的异步回调:

    setTimeout(function() {
        console.log("one");
        setTimeout(function() {
            console.log("two");
            setTimeout(function() {
                console.log("three");
            }, 1000);
        }, 1000);
    }, 1000);
    

      

     好了,ES6 Promises来了:

    function getSum(n1, n2)
    {
        varIsNegative = function()
        {
            return n1 < 0 || n2 < 0;
        }
        
        var promise = new Promise(function(resolve, reject) {
            if (varIsNegative())
            {
                reject(Error("Negatives not supported."));
            }
            resolve(n1 + n2);
        });
        
        return promise;
    }
    
    getSum(5, 7).then(
        function(result) {
            console.log(result);
        }, 
        function(error) {
            console.log(error);
        }
    );
    

      

     现在是ES6 Promises的连续事件(Continuation Events):

    function getSum(n1, n2) {
        var checkNums = function() {
            return n1 < 0 || n2 < 0;
        }
        
        var promise = new Promise(function(resolve, reject) {
            if (checkNums()) {
                reject(Error("Invalid number input."));
            }
            resolve(n1 + n2);
        });
        
        return promise;
    }
    
    getSum(2, 3)
    .then(function(result) {
        console.log(result);
        return getSum(10, 20);    
    }, function(error) {
        console.log(error);
    })
    .then(function(result) {
        console.log(result);
    }, function(error) {
        console.log(error);
    });
    

      

       

  • 相关阅读:
    BZOJ 1597: [Usaco2008 Mar]土地购买
    BZOJ 1005: [HNOI2008]明明的烦恼
    BZOJ 1004: [HNOI2008]Cards
    Burnside引理和Polya定理
    BZOJ 1003: [ZJOI2006]物流运输
    BZOJ 1002: [FJOI2007]轮状病毒
    BZOJ 1001: [BeiJing2006]狼抓兔子
    网络流 最大流dinic算法解释
    51nod 1299 监狱逃离
    2017.11.26【清华集训2017】模拟
  • 原文地址:https://www.cnblogs.com/jinzd/p/7613383.html
Copyright © 2011-2022 走看看