一、加载图片
const preloadImage=function(path){
return new Promise(function(resolve,reject){
var img=new Image();
img.onload=resolve;
img.onerror=reject;
img.src=path;
});
};
二、实现AJAX操作
var getJSON=function(url){
var promise=new Promise(function(resolve,reject){
var xhr=new XMLHttpRequest();
xhr.open('GET',url);
xhr.onreadystatechange=function(){
if (xhr.readyState===4) {
if (xhr.status>=200&&xhr.status<300||xhr.status===304) {
resolve(xhr.responseText);
}else{
reject(new Error(xhr.statusText));
}
}
};
xhr.responseType='json';
xhr.setRequestHeader('Accept','application/json');
xhr.send();
});
return promise;
}
调用getJSON函数:
getJSON(url).then(function(json){
console.log('成功'+json);
}).catch(function(error){
console.log('失败'+error);
});