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)
				})
			})
相关推荐
太阳伞下的阿呆2 天前
HttpClient、OkHttp 和 WebClient
okhttp·httpclient·webclient
2503_928411562 天前
9.8 ajax+php基础语法
ajax·okhttp·php
Yvonne爱编码3 天前
简述ajax、node.js、webpack、git
前端·git·ajax·webpack·node.js·visual studio
小妖怪的夏天3 天前
react native 出现 FATAL EXCEPTION: OkHttp Dispatcher
react native·react.js·okhttp
上单带刀不带妹5 天前
Node.js 的模块化规范是什么?CommonJS 和 ES6 模块有什么区别?
前端·node.js·es6·模块化
长城20246 天前
jQuery的$.Ajax方法分析
ajax·jquery·异步提交
芜青7 天前
JavaScript手录进阶01-跨域问题
开发语言·javascript·ajax·ecmascript
长城20247 天前
JavaScript中的XMLHttpRequest对象分析
开发语言·javascript·ajax·xmlhttprequest·xhr·ajax技术
teeeeeeemo8 天前
前端模块化(commonJS和ES Module)
前端·笔记·es6·前端模块化