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

异步Promise

时间:2014-12-30 00:28:12      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

(function(w){
            function Promise(fn){
                return this instanceof Promise ? this.init(fn) : new Promise(fn);
            }
            Promise.fulfill = function(m){return m;};
            Promise.reject = function(m){throw m;};
            Promise.map = {
                resolve: "onFulfill",
                reject: "onReject"
            }
            //异步自动生成promise并执行
            Promise.resolve = function(fn){
                var p = new Promise();
                setTimeout(function(){
                    p.resolve();
                },0);
                if(fn)
                    p.callback["onFulfill"] = fn;
                return p;
            }
            Promise.prototype = {
                init: function(fn){
                    var that = this;
                    this.state = ‘pending‘;
                    this.callback = {
                        onFulfill: Promise.fulfill,
                        onReject: Promise.reject
                    };
                    this.dirty = false;
                    this._next = null;
                    setTimeout(function(){
                        fn && fn.call(that,that.resolve,that.reject);
                    },0)

                },
                then: function(onFulfill,onReject){
                    return post.call(this,onFulfill,onReject);
                },
                wait: function(mills){ //promise链在wait处被分裂成2段
                    var p = new Promise(),
                            start = new Date().getTime();
                    var id = setTimeout(function(){ //传入时间
                        p.resolve([this.val,new Date().getTime() - start])
                    },mills);
                    p.cancel = function(){
                        clearTimeout(id);
                    }
                    return p;
                },
                all: function(){
                    var p = new Promise(),
                            args;
                    var counter = 0,ret = [];//收集结果,并传给p
                    var v,fn; //传入的函数,执行该函数,将结果保存至ret
                    if(arguments.length > 1){
                        args = [].slice.apply(arguments)
                    }else if({}.toString.call(arguments[0]) == "[object Array]"){
                        args = arguments[0];
                    }
                    for(var i=0,len=args.length;i<len;i++){
                        if(typeof args[i] == "function"){
                            args[i] = Promise.resolve(args[i]);
                        }

                        fn = args[i].callback.onFulfill;
                        v = fn.call(args[i]);
                        (function(v){
                            args[i].then(function(){
                                ret.push(v);

                                if(--counter <= 0){
                                    ret.length = len;
                                    p.resolve(ret);
                                }
                            },function(){
                                p.reject();
                            });

                        })(v)
                        counter++;
                    }
                    return p;
                }
            }
            function post(onFulfill,onReject,onNotify,onComplete){
                var p = new Promise(),
                        that = this;
                if(arguments.length <= 2){
                    that._next = p;
                    that.callback["onFulfill"] = onFulfill;
                    that.callback["onReject"] = onReject;
                    this.dirty = true;
                }
                return p;
            }
            function fire(promise,method){
                var next = "resolve",val,
                        args = arguments[2];
                if(promise.state == "pending"){
                    try{
                        this.val = val = promise.callback[Promise.map[method]].apply(promise,args);
                        promise.state = method;
                    }catch(e){
                        this.val = val = e;
                        next = "reject";
                    }

                    if(val && isPromise(val)){
                        val._next = promise._next;
                    }else{
                        if(promise._next){
                            fire(promise._next,next,[val]);
                        }
                    }

                }
                return promise;
            }
            function isPromise(o){
                return o && typeof o == "object" && o.then && typeof o.then == "function";
            }
            "reject,resolve".replace(/\w+/g,function(m){
                Promise.prototype[m] = function(){
                    return fire(this,m,arguments);
                }
            })

            w.Promise = Promise;
        })(window)
        function f1(i){console.log("f1",i);return "f1 generate"}
        function f2(i){console.log("f2",i);return "f2 generate"}
        function f2e(i){console.log("err:",i)}
        function f3(){setTimeout(function(){console.log(‘f3‘)},2000);return ‘f3‘}
        new Promise(function(){
        //    console.log(this)
            this.resolve("start:")
        }).all(f1,f3).then(f2)

 

 

实例:

技术分享
var getJson = function(url){
            return new Promise(function(resolve,reject){
                var xhr = new XMLHttpRequest();
                if(!window.Promise)return;
                xhr.open(‘get‘,url);
                xhr.onreadystatechange = function(e){
                    if(xhr.readyState == 4){
                        if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                            resolve(xhr.responseText);
                        }else{
                            reject(new Error(‘response error‘));
                        }
                    }
                };
                xhr.onerror = function(e){
                    reject(new Error(‘ajax error‘));
                }
                xhr.send();
            });
        };

        var body = document.body;
        var addHtml = function(html){
            if(typeof  html != ‘string‘) return;
            var p = document.createElement(‘p‘);
            p.textContent = html;
            body.insertBefore(p,loading);
        };
        var addHead = function(html){
            if(typeof html !== ‘string‘) return;
            var h = document.createElement(‘h2‘);
            h.textContent = html;
            body.insertBefore(h,loading);
        }
        var log = function(msg){console.log(msg)};
        var loading = document.getElementById(‘loading‘);

/*        getJson(‘../json/head.json‘).then(JSON.parse).then(function(html){
            addHead(html.content);
            Promise.all(html.urls.map(getJson)).then(function(arr){
                arr.forEach(function(content){
                    addHtml(JSON.parse(content).content);
                })
            }).catch(function(e){
                log(‘error in loading content: ‘+ e);
            })
        }).catch(function(e){
            log(‘error: ‘ + e);
        }).then(function(){
            loading.style.display = ‘none‘;
        })*/

        getJson(‘../json/head.json‘).then(JSON.parse).then(function(html){
            addHead(html.content);
            var promise = Promise.resolve();
            html.urls.forEach(function(url,i){
                promise = promise.then(function(){
                    return getJson(url);
                }).then(JSON.parse).then(function(html){
                    addHtml(html.content);
                }).catch(function(e){
                    log(‘error in loading body: ‘+ e );
                }).then(function(){
                    if(i == html.urls.length-1)
                        loading.style.display = ‘none‘;
                })
            })
        })
View Code

 

异步Promise

标签:

原文地址:http://www.cnblogs.com/accordion/p/4192689.html

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