Promise应用实例

1、Promise 改写Ajax

原生Ajax:

var ajax={
 		get:function(url,fn){
 			var xhr=new XMLHttpRequest();
 			xhr.open('GET',url,true);
 			xhr.onreadystatechange=function(fn){
 				if(xhr.readyState==4&&xhr.status==200){
 					fn.call(this,JSON.parse(xhr.responseText));
 				}
 			}
 			xhr.send();
 		},
 		post:function(url,fn,data){
 			var xhr=new XMLHttpRequest();
 			xhr.open('POST',url,true);
 			xhr.setRequestHeader("Content-type",'x-www-form-urlencoded');
 			xhr.onreadystatechange=function(fn){
 				if(xhr.readyState==4&&xhr.status==200){
 					fn.call(this,JSON.parse(xhr.responseText));
 				}
 			}
 			xhr.send(data);
 		}
 	}

promise改写之后的Ajax:

    const ajaxPromise=(param)=>{
        return new Promise((resolve,reject)=>{
            var xhr=new XMLHttpRequest();
            xhr.open(param.type,param.url,true); 
            xhr.send();
            xhr.onreadystatechange=()=>{
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        resolve(JSON.parse(xhr.responseText))
                    }else{
                        reject("error");
                    }
                }
            }
            
        })
    }
   ajaxPromise({type:'get',url:'goods.json'}).then(function(data){console.log(data)})

2、Promise实现多图预加载

  function preLoadImg(source){
    let pr=[];
    source.forEach(function(url){
        let p=LoadImage(url)
            .then(img=>this.images.push(img))
            .catch(err=>console.log(err))
        pr.push(p);
    })
    Promise.all(pr).then(()=>{})
   }
   function loadImage(url){
    retuen new Promise((resolve,reject)=>{
        let img=new Image();
        img.()=>resolve(img);
        img.reject;
        img.src=url;
    })
   }

参考地址:https://www.cnblogs.com/zhangyubao/p/7003746.html

你可能感兴趣的:(Promise应用实例)