1、自定义(手写)promise–定义整体结构
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./js/jquery.js"></script>
<script src="./js/mypromise.js"></script>
<title>Title</title>
</head>
<body>
<h3>发送ajax请求</h3>
<button id="send_ajax">发送ajax请求</button>
<script>
$('#send_ajax').click(function(){
const promise=new Promise((resolve,reject)=>{
resolve('ok')
})
promise.then((value)=>{
console.log(value)
},(reason)=>{
console.log(reason)
})
})
</script>
</body>
</html>
2、创建类及then方法
js/mypromise.js
步骤:
- 1、创建Promise类,形参为构造器函数,并给创建自定义的then函数。这里then函数是在类原型上建立的
//相当于重写promise
//excutor为执行器函数
function Promise(excutor){
}
//创建then函数,形参为对应resolve和reject的回调函数
Promise.prototype.then=function(onResolved,onRejected){
}
3、创建执行器函数
创建执行器函数的逻辑, 这里要执行执行器函数
```php
//相当于重写promise
function Promise(excutor){
//同步调用执行器函数
function resolve (data) {
}
function reject (data) {
}
//这里要执行这个执行器函数
excutor(resolve,reject)
}
Promise.prototype.then=function(onResolved,onRejected){
}
4、添加并修改PromiseState及PromiseResult属性
Promise有两个重要属性,分别是PromiseState及PromiseResult,一个标识promise的状态,一个用来在promise与then方法之间传值,
这里分别给他们赋值初始状态,然后再resolve和reject函数中分别修改值
//相当于重写promise
function Promise(excutor){
//添加属性
this.PromiseState='pending'
this.PromiseResult=''
const that=this
//同步调用执行器函数
function resolve (data) {
//修改对象的状态。promiseState
that.PromiseState='fulfilled'
//设置对象结果值promiseReuslt
that.PromiseResult=data
}
function reject (data) {
that.PromiseState='rejected'
that.PromiseResult=data
}
//这里要执行这个执行器函数
excutor(resolve,reject)
}
Promise.prototype.then=function(onResolved,onRejected){
}
此刻Promise实例里拥有的内容
5、添加异常处理逻辑
给Promise类添加异常处理逻辑,实际就是设置throw,由于是抛异常,实际就是在对执行器函数的执行进行try…catch操作
而cath捕获异常实际就是失败,因此直接执行reject即可
//相当于重写promise
function Promise(excutor){
//添加属性
this.PromiseState='pending'
this.PromiseResult=''
const that=this
//同步调用执行器函数
function resolve (data) {
//修改对象的状态。promiseState
that.PromiseState='fulfilled'
//设置对象结果值promiseReuslt
that.PromiseResult=data
}
function reject (data) {
that.PromiseState='rejected'
that.PromiseResult=data
}
//这里要执行这个执行器函数
try{
excutor(resolve,reject)
}
catch (e) {
reject(e)//
}
}
Promise.prototype.then=function(onResolved,onRejected){
}
6、PromiseState状态只能改变一次的逻辑
resolve和reject是互斥的,状态只能改变一次,因此要确保状态只能改变一次
方法是进入resolve和reject前去和‘pending’值进行比较,如果不等于pending,则不再修改,直接return
//相当于重写promise
function Promise(excutor){
//添加属性
this.PromiseState='pending'
this.PromiseResult=''
const that=this
//同步调用执行器函数
function resolve (data) {
if (that.PromiseState!=='pending'){
return
}
//修改对象的状态。promiseState
that.PromiseState='fulfilled'
//设置对象结果值promiseReuslt
that.PromiseResult=data
}
function reject (data) {
if (that.PromiseState!=='pending'){
return
}
that.PromiseState='rejected'
that.PromiseResult=data
}
//这里要执行这个执行器函数
try{
excutor(resolve,reject)
}
catch (e) {
reject(e)//
}
}
Promise.prototype.then=function(onResolved,onRejected){
}
后续第七部见下一个博文
版权声明:本文为weixin_43745804原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。