Promise 实例化
const P = new Promise(function(resolve, reject){ setTimeout(function(){ //let data = '数据读取成功'; //resolve(data);//将成功函数赋予resolve属性 let err = " 数据读取失败" reject(err);//将失败函数赋予resolve属性
},1000)
}
//测试的情况下,用那个,显示哪个,目前代码是激活失败状态
调用promise对象 的then方法, 从而实现坚挺成功失败
P.then(function(value){ console.log(value) },function(error){ console.log(error)
console.error(error) })
promise 封装ajax
const url = 'https://api.apiopen.top/getJoke' const ajax = new Promise((resolve,reject) => { //1. 创建对象 const xhr = new XMLHttpRequest(); //2. 初始化 xhr.open("GET",url); //3. 发送 xhr.send(); //4. 绑定时间,处理相应结果 xhr.onreadystatechange = function(){ //判断结果状态 if(xhr.readyState === 4){ //判断响应状态吗200-290 if(xhr.status >=200 && xhr.status<300){ //成功回调 resolve(xhr.response); } else{ //失败回调 reject(xhr.status) } } } }); //指定回调 ajax.then(function(res){ console.log(res) },function(error){ console.error(error); })
//ES6 写法
/*
ajax.then(res=>{
console.log(res)
},error=>{
console.error(error);
})
*/