js的promise应用

来源:互联网 发布:美中国际 知乎 编辑:程序博客网 时间:2024/05/22 03:19

1.异步加载图片

function loadImageAsync(url){  return new Promise(function (resolve,reject){      var img=new Image();      img.onload=function() {            resolve(img);      };      img.onerror=function (){            reject(new Error("could not load image"+url));      };      img.src=url;  });}loadImageAsync("http://img.taopic.com/uploads/allimg/120727/201995-120HG1030762.jpg").then(function () {    console.log("sucess");},function (error) {  console.log(error);});



2.实现AJAX请求


var getjson=function(url){    return  new Promise(function(resolve,reject){                      var xhr=new XMLHttpRequest();           xhr.open("GET",url, true);           xhr.onreadystatechange=handler;           xhr.responseType="json";           xhr.setRequestHeader("Accept","application/json");           xhr.send();          function handler(){            if(this.readyState!==4){              return;            }            if ((this.status>=200&& this.status<300)||this.status===304) {              reslove(this.responseText);            }else{              reject(new Error(this.statusText));            }          }    });};getjson("/post.json").then(function(json){     console.log("content"+json);},function (error) {  console.error('出错了', error);});



原创粉丝点击