函数处理和方法
1.使用Promise解决异步编程
Promise是解决异步编程问题的一种方案
从语法上讲 promise是一个对象 通过这个对象 我们可以获取异步操作的信息
var promise = new Promise((resolve, reject) => {
var random = Math.random();
console.log(random);
setTimeout(() => {
if (random > 0.5) {
resolve({
status: 1, msg: "响应成功" });
} else {
reject({
status: 0, msg: "响应失败" });
}
}, 1000)
})
调用promise的than方法
promise.then(data => {
console.log(data);
}).catch(error => {
console.log(error);
})
console.log(111);
2.使用Promise封装ajax
function toData(obj) {
//声明一个数组 来装每一组的数据
var arr = [];
if (obj !== null) {
for (var key in obj) {
let str = key + "=" + obj[key];
arr.push(str);
}
return arr.join("&");
}
}
function ajax(obj) {
return new Promise(function (resolve, rejevct) {
//给ajax所需要的参数设置默认值
obj.type = obj.type || "get";
obj.async = obj.async || "trie";
obj.dataType = obj.dataType || "json";
obj.data = ppbj.data || null;
//开始发送ajax请求
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
//IE低版本的浏览器
xhr = new ActiveXObject("Microsoft.XMLHttp")
}
// 判断是post请求 还是get请求
if (obj.type === "post") {
xhr.open(obj.type, obj.url, obj.async);
// 设置请求头