//Promise使用示例
new
Promise(function(resolve,reject){ setTimeout(function(){ var ret = "异步1执行成功!"; console.log(ret); resolve(ret); },2000); }) .then(function(msg){ return new Promise(function(resolve,reject){ setTimeout(function(){ var ret = "异步2执行成功!"; console.log(ret); ret +="->"+msg; resolve(ret); },2000); }) }) .then(function(msg){ return new Promise(function(resolve,reject){ setTimeout(function(){ var ret = "异步3执行成功!"; console.log(ret); ret +="->"+msg; resolve(ret); },2000); }) }) .then(function(msg){ console.log(msg); })

 

Promise 辅助工具
      if(!Promise.wrap){
            Promise.wrap  = function(fn){
                return function(){
                    var args = [].slice.call(arguments);
                    return new Promise(function(resolve,reject){
                        fn.apply(null,args.concat(function(err,v){
                            if(err){
                                reject(err);
                            }
                            else{
                                resolve(v);
                            }
                        }));
                    });
                };
            };
        }
        

        function _ajax(arg,callback){
            $.ajax({
                url:arg.url,
                data:arg.data,
                type:arg.type,
                //........
                success:function(data, textStatus, jqXHR){
                    callback(null,data);
                },
                error:function(xhr){
                    callback(xhr,null);
                }
            });
        }

        var request = Promise.wrap(_ajax); 
        request({
            type: "POST",
            url: "some.php",
            data: "name=John&location=Boston",
        }).then(function(msg){
            
        });

 异步迭代生成器使用示例

    function request(x,y){
        $.ajax({
            url:"test.php",
            type:'post',
            data:{
                x:x,
                y:y,
            },
            success:function(result,status,xhr){
               it.next(result);
            },
            error:function(xhr){
               it.throw(xhr.statusText);
            }
        });
    }
    
    function *main (){
        try{
            var ret  = yield request(11,13);
            console.log(ret);
        }catch(err){
            console.log(err);
        }
        
    }

    var it = main();
    it.next();

 

posted on 2018-07-19 19:48  kerryk  阅读(124)  评论(0编辑  收藏  举报