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)
				})
			})
相关推荐
木头程序员3 小时前
前端(包含HTML/JavaScript/DOM/BOM/jQuery)基础-暴力复习篇
开发语言·前端·javascript·ecmascript·es6·jquery·html5
Amumu121381 天前
React 前端请求
前端·react.js·okhttp
3824278271 天前
JS表单提交:submit事件的关键技巧与注意事项
前端·javascript·okhttp
qq_406176142 天前
关于JavaScript中的filter方法
开发语言·前端·javascript·ajax·原型模式
赵民勇2 天前
ES6中的const用法详解
javascript·es6
赵民勇2 天前
JavaScript中的this详解(ES5/ES6)
前端·javascript·es6
起名时在学Aiifox4 天前
从零实现前端数据格式化工具:以船员经验数据展示为例
前端·vue.js·typescript·es6
LongtengGensSupreme4 天前
开放所有跨域 ----前端和后端
前端·后端·ajax·vue·api·jquery
啥都不懂的小小白4 天前
ES6常用新特性
开发语言·javascript·es6
阿珊和她的猫5 天前
从 AMD 到 ES6 模块化:前端模块化的演进之路
前端·ecmascript·es6