ES6 promise 的一些常用方法
var getJSON=function(url){
var promise=newPromise(function(resolve,reject{
?var ? client=newXMLHttpRequest();
client.open("GET",url);
client.onreadystatechange=handler;
client.responseType="json";
client.setRequestHeader("Accept","application/json");
client.send();
function handler(){
if(this.readyState!==4)
{
return;
}
if(this.status===200{
resolve(this.response);
}else{
reject(newError(this.statusText));
}};
});
returnpromise;
};
getJSON("/posts.json").then(function(json){console.log('Contents: '+json);
},function(error){console.error('出錯了',error);
});
上面代碼中,getJSON是對XMLHttpRequest對象的封裝,用于發出一個針對JSON數據的HTTP請求,并且返回一個Promise對象。需要注意的是,在getJSON內部,resolve函數和reject函數調用時,都帶有參數。