js的promise應用

1.異步加載圖片

function loadImageAsync(url){
  return new Promise(function (resolve,reject){
      var img=new Image();
      img.οnlοad=function() {
            resolve(img);
      };
      img.οnerrοr=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);
});



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章