您现在的位置:首页 >> 前端 >> 内容

Promise对象的简单应用

时间:2017/9/2 9:27:00 点击:

  核心提示:一、加载图片const preloadImage=function(path){ return new Promise(function(resolve,reject){ var img=new I...

一、加载图片

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);
});

Tags:PR RO OM MI 
作者:网络 来源:黎舒何