ES6新增promise(异步编程新解决方案)如何封装ajax?

1.什么是异步?

异步是指从程序在运行过程中可以先执行其他操作。

2.什么是promise?

Promise 是 ES6 引入的异步编程的新解决方案。语法上 Promise 是一个构造函数,用来封装异步 操作并可以获取其成功或失败的结果;

3.promise成功和失败的参数如何接收

  1. Promise 构造函数: Promise (excutor) {};

  2. Promise.prototype.then 方法;接收成功参数(then)

  3. Promise.prototype.catch 方法;接收失败参数(catch)

4.Promise 封装 Ajax 请求:

使用原生进ajax封装:

javascript 复制代码
// 请求地址:https://api.apiopen.top/getJoke 
			const p = new Promise(function(resolve, reason) {
				// 原生请求 
				// 1、创建对象 
				const xhr = new XMLHttpRequest();
				// 2、初始化 
				xhr.open("GET", "https://api.apiopen.top/getJoke");
				// 3、发送 xhr.send(); 
				// 4、绑定事件,处理响应结果 
				xhr.onreadystatechange = function() {
					// 判断状态 
					if (xhr.readyState == 4) {
						// 判断响应状态码 200-299 
						if (xhr.status >= 200 && xhr.status <= 299) {
							// 成功 
							resolve(xhr.response);
						} else {
							// 失败 
							reason(xhr.status);
						}
					}
				}
			});
p.then(function (value) { 
 console.log(value.toString()); 
 }, function (reason) { 
 console.log(reason); // 读取失败 
 }) 

使用jQuery进行封装:

javascript 复制代码
const p = new promise(function(resolve, reject) {
				$.ajax({
					type: ,
					url: ,
					datatype: ,
					async: ,
					headers: {},
					data: {},
					success: (res) => resolve(res),
					error: (err) => reject(err)
				})
			})
相关推荐
Jeled10 小时前
Retrofit 与 OkHttp 全面解析与实战使用(含封装示例)
android·okhttp·android studio·retrofit
Xzh042312 小时前
前后端学习的交界
java·ajax·maven·axios·测试
我登哥MVP1 天前
Ajax 详解
java·前端·ajax·javaweb
Jeled1 天前
Android 网络层最佳实践:Retrofit + OkHttp 封装与实战
android·okhttp·kotlin·android studio·retrofit
仲夏幻境1 天前
js利用ajax同步调用如何
开发语言·javascript·ajax
寒月霜华1 天前
JavaWeb前端-Ajax
ajax
幸运小圣2 天前
Iterator迭代器 【ES6】
开发语言·javascript·es6
蹦极的考拉2 天前
PHPCMS V9 自定义证书查询模块(Ajax+防刷+倒计时)
ajax·证书查询·phpcmsv9表单
幸运小圣2 天前
Set数据结构【ES6】
javascript·数据结构·es6
.生产的驴3 天前
React useEffect组件渲染执行操作 组件生命周期 监视器 副作用
前端·css·react.js·ajax·前端框架·jquery·html5