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)
				})
			})
相关推荐
菥菥爱嘻嘻10 小时前
JS手写代码篇---手写ajax
开发语言·javascript·ajax
coding随想19 小时前
JavaScript ES6 解构:优雅提取数据的艺术
前端·javascript·es6
難釋懷1 天前
Vue解决开发环境 Ajax 跨域问题
前端·vue.js·ajax
androidwork1 天前
OkHttp 3.0源码解析:从设计理念到核心实现
android·java·okhttp·kotlin
前端小崔1 天前
前端面试题之ES6保姆级教程
开发语言·前端·javascript·面试·职场和发展·ecmascript·es6
Lhuu(重开版1 天前
Vue:Ajax
vue.js·ajax·okhttp
书语时2 天前
ES6 Promise 状态机
前端·javascript·es6
全栈陈序员2 天前
前端文件下载常用方式详解
前端·javascript·chrome·ajax·css3·html5·safari
lexiangqicheng3 天前
es6+和css3新增的特性有哪些
前端·es6·css3
知月玄3 天前
网页前端开发(基础进阶4--axios)
okhttp