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

      

       

  • 相关阅读:
    算法问题实战策略 JUMPGAME 记忆化搜索
    算法问题实战策略 TRIANGLEPATH 动态规划入门题
    poj 2785 4 Values whose Sum is 0
    poj 3276 Face The Right Way 递推
    acwing 883. 高斯消元解线性方程组
    acwing 861. 二分图的最大匹配 模板
    Leetcode 42 接雨水 双指针 空间换时间
    LeetCode 1290. 二进制链表转整数
    LeetCode 1291. 顺次数
    <挑战程序设计竞赛> poj 3320 Jessica's Reading Problem 双指针
  • 原文地址:https://www.cnblogs.com/jinzd/p/7613383.html
Copyright © 2011-2022 走看看