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);
    });
    

      

       

  • 相关阅读:
    net core3.1 + electron 9.31.2 项目初始化
    DEV Express控件VScorllBar控件使用
    背包系统学习笔(tu)记(cao)
    C#应该掌握的一些东西
    服务器之间数据库拷贝
    photoshop AdobeCS6分享
    Random的实现原理
    C#利用System.Net发送邮件(带 抄送、密送、附件、html格式的邮件)
    jQuery validate验证控件remote缓存bug
    litrpa1.4版本正式发布了
  • 原文地址:https://www.cnblogs.com/jinzd/p/7613383.html
Copyright © 2011-2022 走看看