码迷,mamicode.com
首页 > 其他好文 > 详细

Promise机制

时间:2017-10-02 23:03:35      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:reject   .com   ima   回调   cte   hat   交互   response   hang   

一why:为什么要使用promise机制?

二what: promise机制是什么?

三how:如何使用promise机制?

为什么要使用promise机制?

 

一why:为什么要使用promise机制?

为了解决js中异步编程的毛病:

   1嵌套太深代码可读性太差

   2并行逻辑必须串行执行

二what: promise机制是什么?

每个promise都有三个状态:pending(默认)、fulfilled(完成)、rejected(失败);默认状态可以转变为完成态或失败态,完成态与失败态之间无法相互转换,转变的过程是不可逆的,转变一旦完成promise对象就不能被修改。通过promise提供的then函数注册onFulfill(成功回调)、onReject(失败回调)、onProgres(进度回调)来与promise交互。Then函数返回一个promise对象(称为promise2,前者成为promise1),promise2受promise1状态的影响,具体请查看A+规范。

 

技术分享

 

三how:如何使用promise机制?

request = function(url, cb, eb) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if ((xhr.status >=200 && xhr.status < 300) || xhr.status === 304) {
                cb(xhr.responseText);
            } else {
                eb(new Error({
                    message: xhr.status
                }));
            }
        }
    };
    xhr.open(‘get‘, url, true);
    xhr.send(null);
}

  




2 request(‘data1.json‘, function(data1){ 3 console.log(data1);//处理data1 4 request(‘data2.json‘, function(data2) { 5 console.log(data2);//处理data2 6 request(‘data3.json‘, function(data3) { 7 console.log(data3);//处理data3 8 9 alert(‘success‘); 10 }, function(err) { 11 console.error(err); 12 }); 13 }, function(err) { 14 console.error(err); 15 }); 16 }, function(err) { 17 console.error(err); 18 });

  promise方式:

request = function(url) {
    var def = new Deferred();

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if ((xhr.status >=200 && xhr.status < 300) || xhr.status === 304) {
                def.resolve(xhr.responseText)
            } else {//简化ajax,没有提供错误回调
                def.reject(new Error({
                    message: xhr.status
                }));
            }
        }
    };
    xhr.open(‘get‘, url, true);
    xhr.send(null);

    return def.promise;
}

request(‘data1.json‘).then(function(data1) {
    console.log(data1);//处理data1
    return request(‘data2.json‘);
}).then(function(data2) {
    console.log(data2);//处理data2
    return request(‘data3.json‘);
}, function(err) {
    console.error(err);
}).then(function(data3) {
    console.log(data3);
    alert(‘success‘);
}, function(err) {
    console.error(err);
});

  

//并行逻辑串行执行
request(‘data1‘, function(data1) {
    request(‘data2‘, function(data2) {
        request(‘data3‘, function(data3) {
            console.log(data1, data2, data3);//处理全部数据

            alert(‘success‘);
        }, function(err) {
            console.error(err);
        });
    }, function(err) {
        console.error(err);
    });
}, function(err) {
    console.error(err);
});

  promise方式

//所有异步操作都完成时,进入完成态,
//其中一项异步操作失败则进入失败态
all = function(requestArray) {
    // var some = Array.prototype.some;
    var def = new Deferred();
    var results = [];
    var total = 0;
    requestArray.some(function(r, idx) {
        //为数组中每一项注册回调函数
        r.then(function(data) {
            if (def.promise.isPending()) {
                total++;
                results[idx] = data;

                if (total === requestArray.length) {
                    def.resolve(results);
                }
            }
        },  function(err) {
            def.reject(err);
        });
        //如果不是等待状态则停止,比如requestArray[0]失败的话,剩下数组则不用继续注册
        return !def.promise.isPending();
    });

    return def.promise;
}

all(
    [request(‘data1.json‘),
    request(‘data2.json‘),
    request(‘data3.json‘)]
    ).then(
        function(results){
            console.log(results);// 处理data1,data2,data3
            alert(‘success‘);
    }, function(err) {
        console.error(err);
    });

  

 

Promise机制

标签:reject   .com   ima   回调   cte   hat   交互   response   hang   

原文地址:http://www.cnblogs.com/superAnny/p/7622862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!