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)
				})
			})
相关推荐
sugar__salt10 小时前
Vue.js 前置知识:ES6+ 核心特性完全指南
前端·javascript·vue.js·vue·es6
zhangjin11202 天前
Okhttp系列:POST请求
okhttp
zzx2006__3 天前
Ajax➕node.js➕webpack
ajax·webpack·node.js
এ慕ོ冬℘゜4 天前
深入理解 JavaScript 事件体系:Window、鼠标与键盘事件详解
开发语言·javascript·okhttp
南川琼语4 天前
HTTP——AJAX
前端·javascript·ajax
肖志-AI全栈6 天前
从零讲透 Ajax:XHR、Fetch、JSON 序列化到异步编程全链路
前端·ajax·json
牢七7 天前
wordpress
okhttp
脉动数据行情10 天前
Java OkHttp 完整封装 GC COMEX 美黄金实时盘口定时拉取工具类
java·okhttp·comex 黄金·外盘贵金属
帅次11 天前
Android 高级工程师面试:网络与数据层 近1年高频追问 18 题
android·网络·okhttp·面试·retrofit·gilde
Java面试题总结12 天前
fastadmin 新手部分功能点
okhttp