Promise的理解以及ajax封装

Promise【无论做项目,还是面试都是很常见的】
 面试官可能会问:Promise你怎么理解的,在项目中用过没有

  1.Promise是一种为了避免回调地狱的异步解决方案
  2.Promise是一种状态机:
  
        pending(进行中)、fulfilled(已成功)和rejected(已失败)
        只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。

  3.Promise暴露的API
.then(函数1,函数2)

函数1:表示成功返回
函数2:代表失败返回

例如:

promise.then(function(value) {
       // success
}, function(error) {
    // failure
});
.catch:失败处理

ajax(url,‘GET’) //通常成功返回的处理 .then(res=>{ console.log(‘获取数据::’,res) }) //失败处理 .catch(error=>{ console.log(‘失败的处理’,error) })

.all:主要用于同时处理多个接口的请求时使用,只有多个接口同时成功返回时才可以
Promise.all([p1(),p2()])
   .then(result=>{
      //其中result返回的是一个数组
      console.log('result:',result);
});
.finally:无论成功和失败,都会被执行
.race:请求多个接口时,只要有一个状态改变,就会提前返回
Promise.race([p2(),p1()]) .then(result=>{
 console.log('result:',result);
})
完整版本:ajax封装
function ajax(url = '', data = {}, type = 'GET', method = 'fetch') => {
	type = type.toUpperCase();
	url = baseUrl + url;

	if (type == 'GET') {   //?id=1001&name=alice  {id:1001,name:'alice'}
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}

	if (window.fetch && method == 'fetch') {
		let requestConfig = {
			credentials: 'include',
			method: type,
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			mode: "cors",
			cache: "force-cache"
		}

		if (type == 'POST') {
			Object.defineProperty(requestConfig, 'body', {
				value: JSON.stringify(data)
			})
		}
	
		try {
			const response = await fetch(url, requestConfig);
			const responseJson = await response.json();
			return responseJson
		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, url, true);
			requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response
						if (typeof obj !== 'object') {
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
						reject(requestObj)
					}
				}
			}
		})
	}
}
写的不好多多见谅~
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值