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

  

 

 

 

 

 

   

posted @ 2017-09-30 01:43  Jinzd  阅读(260)  评论(0编辑  收藏  举报