异步操作
promise封装fs文件操作
原始:
const fs =require('fs')
fs.readFile(url,(err,data)=>{
//如果出错则抛出错误
if(err) throw err
//输出文件内容
console.log(data.toString())
})
promise:
const fs =require('fs')
let p=new Promise((resolve,reject)=>{
fs.readFile(url,(err,data)=>{
//如果失败
if(err) reject(err)
//如果成功
resolve(data)
})
})
p.then(value=>{
console.log(value.toString())
},reason={
console.log(reason)
})
promise封装AJAX
原始:
const xhr=new XMLHttpRequest()
xhr.open('GET',url)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState===4){
if(xhr.status>=200 && xhr.status < 300){
console.log(xhr.response)
}else{
console.log(xhr.status)
}
}
}
封装:
function sendAJAX(url){
return new Promise((resolve,reject)=>{
const xhr = new XMLHttpRequest()
xhr.open('GET',url)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState===4){
if(xhr.status>=200 && xhr.status < 300){
resolve(xhr.response)
}else{
reject(xhr.status)
}
}
}
})
}
Promise状态
实例对象中的一个属性 [PromiseState]
- pending 未决定的
- resolved / fulfilled 成功
- rejected 失败
只能由pending转为fulfille 或者 由pending转为rejected
不可逆,只能改变一次
Promise对象的值
实例对象中的另一个属性 [PromiseResult]
保存异步任务【成功或失败】的结果
- resolve
- reject
Promise基本流程
Promise的API
构造函数Promise
Promise.prototype.then
Promise.prototype.catch
catch捕捉失败,实际上也是用then封装而来的
Promise.resolve
返回一个成功的promise对象
注意参数不同会有不同的结果
const p =Promise.resolve(参数)
//如果参数为非Promise类型的对象,则返回结果为成功promise对象
//如果参数为Promise对象,则参数的结果决定resolve的结果
let p1=Promise.resolve(new Promise((resolve,reject)=>{
resolve('OK')
}))
console.log(p1)//状态为fulfilled,值为OK
let p2=Promise.resolve(new Promise((resolve,reject)=>{
reject('ERROR')
}))
//p2状态为rejected,值为ERROR
//由于p2返回错误,所以用catch接收(不然浏览器会报错提醒)
p2.catch(reason=>{
console.log(reason)
})
console.log(p2)//ERROR
Promise.reject
返回一个失败的promise对象
参数不管是什么,结果永远是失败的
Promise.all
接收参数:n个promise数组
返回一个新的promise,只有所有的promise成功,这个新的promise为成功,值为所有成功promise的值组成的数组;
如果n个里面有失败的,这个新的promise失败,值由第一个失败的promise决定
let p1 = new Promise((resolve,reject) => {
resolve('OK1')
})
let p2 = new Promise((resolve,reject) => {
resolve('OK2')
})
let p3 = new Promise((resolve,reject) => {
resolve('OK3')
})
const result = Promise.all([p1,p2,p3])
console.log(result)//状态为fulfilled,值为['OK1','OK2','OK3']
let p4 = new Promise((resolve,reject) => {
reject('error')
})
const result2 = Promise.all([p1,p4,p2,p3])
console.log(result2)//状态为rejected,值为error
Promise.race
接收参数:n个promise数组
返回一个新的promise,第一个promise的结果为最终结果
let p1 = new Promise((resolve,reject) => {
resolve('OK1')
})
let p2 = new Promise((resolve,reject) => {
reject('error')
})
let p3 = new Promise((resolve,reject) => {
resolve('OK3')
})
const result = Promise.race([p1,p2,p3])
console.log(result)//与p1一样,状态为fulfilled,值为OK1
let p4 = new Promise((resolve,reject) => {
setTimeout(() => {
resolve('OK4')
},1000)
})
const result2 = Promise.race([p4,p1,p2,p3])
console.log(result2)//结果与p1一样,因为p4有个定时器,p1先执行
Promise的几个关键问题
怎么改变promise的状态
- 调用resolve函数:pending -->fulfilled
- 调用reject函数:pending -->rejected
- 抛出错误
let p1 = new Promise((resolve,reject) => {
throw '出错了'
})
console.log(p1)//rejected,出错了
一个promise指定(then)多个成功/失败回调函数,都会调用吗
当promise状态改变时都会调用
let p1 = new Promise((resolve,reject) => {
resolve('OK1')
})
p1.then( value => {
console.log('ok')
})
p1.then( value => {
alert('又一次ok')
})
//既会打印,又会出来alert
let p1 = new Promise((resolve,reject) => {
})
p1.then( value => {
console.log('ok')
})
p1.then( value => {
alert('又一次ok')
})
//不会执行
改变状态和指定回调谁先谁后
都有可能。
先改变状态,后指定回调:执行器任务为同步
先指定回调,后改变状态:执行器任务为异步
注意:指定回调不是执行回调,指定回调强调的是先声明then方法
let p1 = new Promise((resolve,reject) => {
resolve('OK')
})
p1.then( value => {
console.log('ok')
console.log(value)
},reason => {
console.log(reason)
})
//结果:ok,OK
let p1 = new Promise((resolve,reject) => {
setTimeout(() => {
resolve('OK')
},1000)
})
p1.then( value => {
console.log('ok')
console.log(value)
},reason => {
console.log(reason)
})
//等一秒,结果:ok,Ok
- 怎么先改变状态再指定回调
①在执行器中直接调用resolve / reject====》同步
②延迟更长时间才调用then - 什么时候才能得到数据
①若先指定的回调:当状态发生改变时,回调函数就会调用,得到数据
②若先改变的状态:当指定回调时,回调函数就会调用,得到数据
promise.then()返回的新promise结果状态由什么决定
由then()指定的回调函数执行的结果决定
①若抛出异常,新promise变为rejected,reason为抛出异常
②若返回的是非promise的任意值,新promise变为resolved,value为返回的值
③若返回的是另一个新promise,此promise的结果就会成为新promise的结果
let p = new Promise((resolve,reject) => {
resolve('OK')
})
//执行then方法
let result = p.then( value => {
//console.log(value)
//1.抛出错误
//throw '出了问题'
//result这个promise对象结果:rejected,值为出了问题
//2.返回非promise类型对象
//return 521
//result这个promise对象结果:fulfilled,值为521
//3.返回的是promise对象
//return new Promise((resolve,reject) => {
// resolve('又来ok')
//})
//result这个promise对象结果:fulfilled,值为又来ok
},reason => {
console.log(reason)
})
console.log(result)
//返回的是promise对象
promise如何串连多个操作任务
①promise的then()返回一个新的promise,可以开成then()的链式调用
②通过then的链式调用串连多个同步/异步任务
let p =new Promise((resolve,reject) => {
setTimeout(() => {
resolve('ok')
},1000)
})
p.then(value => {
return new Promise((resolve,reject) => {
resolve('success')
})
}).then(value =>{
console.log(value) //等1秒,打印success
}).then(value => {
console.log(value)//undefined
})
promise异常传透
①当使用promise的then链式调用时,可以在最后指定失败的回调
②前面任何操作出了异常,都会传到最后失败的回调中处理
let p =new Promise((resolve,reject) => {
setTimeout(() => {
reject('Err')
},1000)
})
p.then(value =>{
console.log(111)
}).then(value => {
console.log(222)
}).then(value => {
console.log(333)
}).catch(reason => {
console.warn(reason)
})
//结果:Err
let p =new Promise((resolve,reject) => {
setTimeout(() => {
resolve('ok')
},1000)
})
p.then(value =>{
throw '失败了'
}).then(value => {
console.log(222)
}).then(value => {
console.log(333)
}).catch(reason => {
console.warn(reason)
})
//结果:失败了
中断promise链
①当使用promise的then链式调用时,在中间中断,不再调用后面的回调函数
②办法:在回调函数中返回一个pending状态的promise对象
let p =new Promise((resolve,reject) => {
setTimeout(() => {
resolve('ok')
},1000)
})
p.then(value =>{
console.log(111)
//有且只有一种方法:返回promise
return new Promise(() => {})
}).then(value => {
console.log(222)
}).then(value => {
console.log(333)
}).catch(reason => {
console.warn(reason)
})
//结果:111
手写promise
1. promise 的参数
完整
class myPromise{
constructor(executor){
// 传参不是一个函数
if(typeof(executor)!='function'){
throw new Error('MyPromise must accept a function as a parameter')
}
}
}
2.同步调用promise的resolve与reject
完整
class myPromise{
constructor(executor){
// 传参不是一个函数
if(typeof(executor)!='function'){
throw new Error('MyPromise must accept a function as a parameter')
}else{
//同步调用 【执行器函数】
executor(this.resolve,this.reject)
}
}
resolve(value){
}
reject(value){
}
}
3.实现resolve和reject函数功能
完整
class myPromise{
constructor(executor){
// 传参不是一个函数
if(typeof(executor)!='function'){
throw new Error('MyPromise must accept a function as a parameter')
}else{
// 添加属性
this.PromiseState='pending'
this.PromiseResult=undefined
// 让resolve和reject的this指向实例对象
this.resolve=this.resolve.bind(this)
this.reject=this.reject.bind(this)
//同步调用 【执行器函数】
executor(this.resolve,this.reject)
}
}
// resolve函数
resolve(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='fulfilled'
// 设置结构值(promiseResult)
this.PromiseResult=value
}
// reject函数
reject(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='rejected'
// 设置结构值(promiseResult)
this.PromiseResult=value
}
}
4.throw抛出异常改变状态
try{
//同步调用 【执行器函数】
executor(this.resolve,this.reject)
}catch(e){
// 遇到throw,调用reject改变状态和值
this.reject(e)
}
完整
class myPromise{
constructor(executor){
// 传参不是一个函数
if(typeof(executor)!='function'){
throw new Error('MyPromise must accept a function as a parameter')
}else{
// 添加属性
this.PromiseState='pending'
this.PromiseResult=undefined
// 让resolve和reject的this指向实例对象
this.resolve=this.resolve.bind(this)
this.reject=this.reject.bind(this)
// try/catch实现throw抛出异常
try{
//同步调用 【执行器函数】
executor(this.resolve,this.reject)
}catch(e){
// 遇到throw,调用reject改变状态和值
this.reject(e)
}
}
}
// resolve函数
resolve(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='fulfilled'
// 设置结构值(promiseResult)
this.PromiseResult=value
}
// reject函数
reject(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='rejected'
// 设置结构值(promiseResult)
this.PromiseResult=value
}
}
5.then方法执行回调
// then函数
then(onResolved,onRejected){
// 调用回调函数
if(this.PromiseState==='fulfilled'){
onResolved(this.PromiseResult)
}
if(this.PromiseState==='rejected'){
onRejected(this.PromiseResult)
}
}
完整
class myPromise{
constructor(executor){
// 传参不是一个函数
if(typeof(executor)!='function'){
throw new Error('MyPromise must accept a function as a parameter')
}else{
// 添加属性
this.PromiseState='pending'
this.PromiseResult=undefined
// 让resolve和reject的this指向实例对象
this.resolve=this.resolve.bind(this)
this.reject=this.reject.bind(this)
// try/catch实现throw抛出异常
try{
//同步调用 【执行器函数】
executor(this.resolve,this.reject)
}catch(e){
// 遇到throw,调用reject改变状态和值
this.reject(e)
}
}
}
// resolve函数
resolve(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='fulfilled'
// 设置结构值(promiseResult)
this.PromiseResult=value
}
// reject函数
reject(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='rejected'
// 设置结构值(promiseResult)
this.PromiseResult=value
}
// then函数
then(onResolved,onRejected){
// 调用回调函数
if(this.PromiseState==='fulfilled'){
onResolved(this.PromiseResult)
}
if(this.PromiseState==='rejected'){
onRejected(this.PromiseResult)
}
}
}
6.异步任务的回调
then函数:
// then函数
then(onResolved,onRejected){
// 调用回调函数
if(this.PromiseState==='fulfilled'){
onResolved(this.PromiseResult)
}
if(this.PromiseState==='rejected'){
onRejected(this.PromiseResult)
}
// 判断pending函数
if(this.PromiseState==='pending'){
// 保存回调函数
this.callback={
// 简写
onResolved,
onRejected
}
}
}
设置属性保存回调
// 声明属性,保存回调
this.callback={}
在resolve调用回调
// resolve函数
resolve(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='fulfilled'
// 设置结构值(promiseResult)
this.PromiseResult=value
// 执行成功的回调
if(this.callback.onResolved){
this.callback.onResolved(value)
}
}
在reject调用回调
// reject函数
reject(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='rejected'
// 设置结构值(promiseResult)
this.PromiseResult=value
if(this.callback.onRejected){
this.callback.onRejected(value)
}
}
完整:
class myPromise{
constructor(executor){
// 传参不是一个函数
if(typeof(executor)!='function'){
throw new Error('MyPromise must accept a function as a parameter')
}else{
// 添加属性
this.PromiseState='pending'
this.PromiseResult=undefined
// 声明属性,保存回调
this.callback={}
// 让resolve和reject的this指向实例对象
this.resolve=this.resolve.bind(this)
this.reject=this.reject.bind(this)
// try/catch实现throw抛出异常
try{
//同步调用 【执行器函数】
executor(this.resolve,this.reject)
}catch(e){
// 遇到throw,调用reject改变状态和值
this.reject(e)
}
}
}
// resolve函数
resolve(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='fulfilled'
// 设置结构值(promiseResult)
this.PromiseResult=value
// 执行成功的回调
if(this.callback.onResolved){
this.callback.onResolved(value)
}
}
// reject函数
reject(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='rejected'
// 设置结构值(promiseResult)
this.PromiseResult=value
if(this.callback.onRejected){
this.callback.onRejected(value)
}
}
// then函数
then(onResolved,onRejected){
// 调用回调函数
if(this.PromiseState==='fulfilled'){
onResolved(this.PromiseResult)
}
if(this.PromiseState==='rejected'){
onRejected(this.PromiseResult)
}
// 判断pending函数
if(this.PromiseState==='pending'){
// 保存回调函数
this.callback={
// 简写
onResolved,
onRejected
}
}
}
}
7.指定多个回调
设置回调属性:
// 声明属性,保存回调
this.callbacks=[]
then保存回调:
// then函数
then(onResolved,onRejected){
// 调用回调函数
if(this.PromiseState==='fulfilled'){
onResolved(this.PromiseResult)
}
if(this.PromiseState==='rejected'){
onRejected(this.PromiseResult)
}
// 判断pending函数
if(this.PromiseState==='pending'){
// 保存回调函数
this.callbacks.push({
// 简写
onResolved,
onRejected
})
}
}
调用回调:
resolve:
resolve(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='fulfilled'
// 设置结构值(promiseResult)
this.PromiseResult=value
// 执行成功的回调
this.callbacks.forEach(item=>{
item.onResolved(value)
})
}
reject:
reject(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='rejected'
// 设置结构值(promiseResult)
this.PromiseResult=value
this.callbacks.forEach(item => {
item.onRejected(value)
})
}
完整
class myPromise{
constructor(executor){
// 传参不是一个函数
if(typeof(executor)!='function'){
throw new Error('MyPromise must accept a function as a parameter')
}else{
// 添加属性
this.PromiseState='pending'
this.PromiseResult=undefined
// 声明属性,保存回调
this.callbacks=[]
// 让resolve和reject的this指向实例对象
this.resolve=this.resolve.bind(this)
this.reject=this.reject.bind(this)
// try/catch实现throw抛出异常
try{
//同步调用 【执行器函数】
executor(this.resolve,this.reject)
}catch(e){
// 遇到throw,调用reject改变状态和值
this.reject(e)
}
}
}
// resolve函数
resolve(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='fulfilled'
// 设置结构值(promiseResult)
this.PromiseResult=value
// 执行成功的回调
this.callbacks.forEach(item=>{
item.onResolved(value)
})
}
// reject函数
reject(value){
// 状态只能改变一次
if(this.PromiseState!=='pending') return
// 设置状态(promiseState)
this.PromiseState='rejected'
// 设置结构值(promiseResult)
this.PromiseResult=value
this.callbacks.forEach(item => {
item.onRejected(value)
})
}
// then函数
then(onResolved,onRejected){
// 调用回调函数
if(this.PromiseState==='fulfilled'){
onResolved(this.PromiseResult)
}
if(this.PromiseState==='rejected'){
onRejected(this.PromiseResult)
}
// 判断pending函数
if(this.PromiseState==='pending'){
// 保存回调函数
this.callbacks.push({
// 简写
onResolved,
onRejected
})
}
}
}
let p = new myPromise((resolve,reject) => {
setTimeout(() => {
// resolve(1)
reject(2)
},1000)
})
p.then(value=>{
console.log(value)
},reason=>{
console.log(reason)
})
p.then(value=>{
console.log('ok')
},reason=>{
console.log('err')
})
console.log(p)
8.同步修改状态then方法结果返回
then:
then(onResolved, onRejected) {
return new myPromise((resolve, reject) => {
// 调用回调函数
if (this.PromiseState === "fulfilled") {
try {
// 获取回调函数的执行结果
let result = onResolved(this.PromiseResult);
// 判断result为promise对象
if (result instanceof myPromise) {
result.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
// result为非promise对象,调用成功
// 结果的状态为成功
resolve(result);
}
} catch (e) {
reject(e);
}
}
if (this.PromiseState === "rejected") {
onRejected(this.PromiseResult);
}
// 判断pending函数
if (this.PromiseState === "pending") {
// 保存回调函数
this.callbacks.push({
// 简写
onResolved,
onRejected,
});
}
});
}
完整
class myPromise {
constructor(executor) {
// 传参不是一个函数
if (typeof executor != "function") {
throw new Error("MyPromise must accept a function as a parameter");
} else {
// 添加属性
this.PromiseState = "pending";
this.PromiseResult = undefined;
// 声明属性,保存回调
this.callbacks = [];
// 让resolve和reject的this指向实例对象
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
// try/catch实现throw抛出异常
try {
//同步调用 【执行器函数】
executor(this.resolve, this.reject);
} catch (e) {
// 遇到throw,调用reject改变状态和值
this.reject(e);
}
}
}
// resolve函数
resolve(value) {
// 状态只能改变一次
if (this.PromiseState !== "pending") return;
// 设置状态(promiseState)
this.PromiseState = "fulfilled";
// 设置结构值(promiseResult)
this.PromiseResult = value;
// 执行成功的回调
this.callbacks.forEach((item) => {
item.onResolved(value);
});
}
// reject函数
reject(value) {
// 状态只能改变一次
if (this.PromiseState !== "pending") return;
// 设置状态(promiseState)
this.PromiseState = "rejected";
// 设置结构值(promiseResult)
this.PromiseResult = value;
this.callbacks.forEach((item) => {
item.onRejected(value);
});
}
// then函数
then(onResolved, onRejected) {
return new myPromise((resolve, reject) => {
// 调用回调函数
if (this.PromiseState === "fulfilled") {
try {
// 获取回调函数的执行结果
let result = onResolved(this.PromiseResult);
// 判断result为promise对象
if (result instanceof myPromise) {
result.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
// result为非promise对象,调用成功
// 结果的状态为成功
resolve(result);
}
} catch (e) {
reject(e);
}
}
if (this.PromiseState === "rejected") {
onRejected(this.PromiseResult);
}
// 判断pending函数
if (this.PromiseState === "pending") {
// 保存回调函数
this.callbacks.push({
// 简写
onResolved,
onRejected,
});
}
});
}
}
let p = new myPromise((resolve, reject) => {
resolve(1);
// reject(2);
});
let result = p.then(
(value) => {
// console.log(value);
// return new myPromise((resolve, reject) => {
// // resolve("success");
// reject("oh, no");
// });
throw "FAIL";
},
(reason) => {
console.log(reason);
}
);
console.log(result);
9.异步修改状态then方法结果返回
例子:
let p = new myPromise((resolve, reject) => {
setTimeout(() => {
reject(2);
}, 1000);
});
let res = p.then(
(value) => {
return "oh,yeah";
},
(reason) => {
console.log(reason);
}
);
console.log(res);
then函数:
then(onResolved, onRejected) {
return new myPromise((resolve, reject) => {
// 调用回调函数
if (this.PromiseState === "fulfilled") {
try {
// 获取回调函数的执行结果
let result = onResolved(this.PromiseResult);
// 判断result为promise对象
if (result instanceof myPromise) {
result.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
// result为非promise对象,调用成功
// 结果的状态为成功
resolve(result);
}
} catch (e) {
reject(e);
}
}
if (this.PromiseState === "rejected") {
onRejected(this.PromiseResult);
}
// 判断pending函数
if (this.PromiseState === "pending") {
// 保存回调函数
this.callbacks.push({
// 简写
onResolved: () => {
try {
// 用箭头函数是为了this指向
// 执行成功的回调函数
let result = onResolved(this.PromiseResult);
if (result instanceof myPromise) {
result.then(
(v) => {
console.log("---------");
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
resolve(result);
}
} catch (e) {
reject(e);
}
},
onRejected: () => {
try {
// 用箭头函数是为了this指向
// 执行成功的回调函数
let result = onRejected(this.PromiseResult);
if (result instanceof myPromise) {
result.then(
(v) => {
console.log("---------");
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
resolve(result);
}
} catch (e) {
reject(e);
}
},
});
}
});
}
10.then封装优化
then(onResolved, onRejected) {
return new myPromise((resolve, reject) => {
// 封装回调函数
let callback = (type) => {
try {
// 获取回调函数的执行结果
let result = type(this.PromiseResult);
// 判断result为promise对象
if (result instanceof myPromise) {
result.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
// result为非promise对象,调用成功
// 结果的状态为成功
resolve(result);
}
} catch (e) {
reject(e);
}
};
// 调用回调函数
if (this.PromiseState === "fulfilled") {
callback(onResolved);
}
if (this.PromiseState === "rejected") {
callback(onRejected);
}
// 判断pending函数
if (this.PromiseState === "pending") {
// 保存回调函数
this.callbacks.push({
// 简写
onResolved: () => {
callback(onResolved);
},
onRejected: () => {
callback(onRejected);
},
});
}
});
}
11.catch方法:异常穿透和值传递
catch函数:
// catch函数
catch(onRejected) {
return this.then(undefined, onRejected);
}
then函数添加回调函数的参数判断:
then(onResolved, onRejected) {
// 判断回调函数参数
if (typeof onRejected !== "function") {
onRejected = (reason) => {
throw reason;
};
}
if (typeof onResolved !== "function") {
onResolved = (value) => value;
}
return new myPromise((resolve, reject) => {
// 封装回调函数
let callback = (type) => {
try {
// 获取回调函数的执行结果
let result = type(this.PromiseResult);
// 判断result为promise对象
if (result instanceof myPromise) {
result.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
// result为非promise对象,调用成功
// 结果的状态为成功
resolve(result);
}
} catch (e) {
reject(e);
}
};
// 调用回调函数
if (this.PromiseState === "fulfilled") {
callback(onResolved);
}
if (this.PromiseState === "rejected") {
callback(onRejected);
}
// 判断pending函数
if (this.PromiseState === "pending") {
// 保存回调函数
this.callbacks.push({
// 简写
onResolved: () => {
callback(onResolved);
},
onRejected: () => {
callback(onRejected);
},
});
}
});
}
完整
class myPromise {
constructor(executor) {
// 传参不是一个函数
if (typeof executor != "function") {
throw new Error("MyPromise must accept a function as a parameter");
} else {
// 添加属性
this.PromiseState = "pending";
this.PromiseResult = undefined;
// 声明属性,保存回调
this.callbacks = [];
// 让resolve和reject的this指向实例对象
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
// try/catch实现throw抛出异常
try {
//同步调用 【执行器函数】
executor(this.resolve, this.reject);
} catch (e) {
// 遇到throw,调用reject改变状态和值
this.reject(e);
}
}
}
// resolve函数
resolve(value) {
// 状态只能改变一次
if (this.PromiseState !== "pending") return;
// 设置状态(promiseState)
this.PromiseState = "fulfilled";
// 设置结构值(promiseResult)
this.PromiseResult = value;
// 执行成功的回调
this.callbacks.forEach((item) => {
item.onResolved(value);
});
}
// reject函数
reject(value) {
// 状态只能改变一次
if (this.PromiseState !== "pending") return;
// 设置状态(promiseState)
this.PromiseState = "rejected";
// 设置结构值(promiseResult)
this.PromiseResult = value;
this.callbacks.forEach((item) => {
item.onRejected(value);
});
}
// then函数
then(onResolved, onRejected) {
// 判断回调函数参数
if (typeof onRejected !== "function") {
onRejected = (reason) => {
throw reason;
};
}
if (typeof onResolved !== "function") {
onResolved = (value) => value;
}
return new myPromise((resolve, reject) => {
// 封装回调函数
let callback = (type) => {
try {
// 获取回调函数的执行结果
let result = type(this.PromiseResult);
// 判断result为promise对象
if (result instanceof myPromise) {
result.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
// result为非promise对象,调用成功
// 结果的状态为成功
resolve(result);
}
} catch (e) {
reject(e);
}
};
// 调用回调函数
if (this.PromiseState === "fulfilled") {
callback(onResolved);
}
if (this.PromiseState === "rejected") {
callback(onRejected);
}
// 判断pending函数
if (this.PromiseState === "pending") {
// 保存回调函数
this.callbacks.push({
// 简写
onResolved: () => {
callback(onResolved);
},
onRejected: () => {
callback(onRejected);
},
});
}
});
}
// catch函数
catch(onRejected) {
return this.then(undefined, onRejected);
}
}
let p = new myPromise((resolve, reject) => {
// reject(2);
resolve("ok");
});
p.then()
.then((value) => {
console.log(111);
})
.then((value) => {
console.log(222);
})
.then((value) => {
console.log(333);
})
.catch((reason) => {
console.warn(reason);
});
12.resolve方法封装
myPromise.resolve = function (value) {
return new myPromise((resolve, reject) => {
if (value instanceof myPromise) {
value.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
resolve(value);
}
});
};
13.reject方法封装
myPromise.reject = function (reason) {
return new myPromise((resolve, reject) => {
reject(reason);
});
};
14.all方法封装
myPromise.all = function (promise) {
return new myPromise((resolve, reject) => {
// 声明成功对象的个数
let count = 0;
// 声明成功结果的数组
let arr = [];
// 遍历
for (let i = 0; i < promise.length; i++) {
promise[i].then(
(v) => {
// 对象状态为成功
// 每个promise中都成功就调用resolve
count++;
arr[i] = v;
if (count === promise.length) {
resolve(arr);
}
},
(r) => {
reject(r);
}
);
}
});
};
15.race方法封装
myPromise.race = function (promise) {
return new myPromise((resolve, reject) => {
for (let i = 0; i < promise.length; i++) {
promise[i].then(
(v) => {
// 修改返回对象的状态为成功
resolve(v);
},
(r) => {
// 修改返回对象的状态为失败
reject(r);
}
);
}
});
};
16.then指定的为微任务
例子:
let p1 = new myPromise((resolve, reject) => {
resolve("ok1");
console.log(111);
});
p1.then((value) => {
console.log(222);
});
console.log(333);
//结果为:111,333,222
最终完整版
class myPromise {
constructor(executor) {
// 传参不是一个函数
if (typeof executor != "function") {
throw new Error("MyPromise must accept a function as a parameter");
} else {
// 添加属性
this.PromiseState = "pending";
this.PromiseResult = undefined;
// 声明属性,保存回调
this.callbacks = [];
// 让resolve和reject的this指向实例对象
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
// try/catch实现throw抛出异常
try {
//同步调用 【执行器函数】
executor(this.resolve, this.reject);
} catch (e) {
// 遇到throw,调用reject改变状态和值
this.reject(e);
}
}
}
// resolve函数
resolve(value) {
// 状态只能改变一次
if (this.PromiseState !== "pending") return;
// 设置状态(promiseState)
this.PromiseState = "fulfilled";
// 设置结构值(promiseResult)
this.PromiseResult = value;
setTimeout(() => {
// 执行成功的回调
this.callbacks.forEach((item) => {
item.onResolved(value);
});
});
}
// reject函数
reject(value) {
// 状态只能改变一次
if (this.PromiseState !== "pending") return;
// 设置状态(promiseState)
this.PromiseState = "rejected";
// 设置结构值(promiseResult)
this.PromiseResult = value;
setTimeout(() => {
this.callbacks.forEach((item) => {
item.onRejected(value);
});
});
}
// then函数
then(onResolved, onRejected) {
// 判断回调函数参数
if (typeof onRejected !== "function") {
onRejected = (reason) => {
throw reason;
};
}
if (typeof onResolved !== "function") {
onResolved = (value) => value;
}
return new myPromise((resolve, reject) => {
// 封装回调函数
let callback = (type) => {
try {
// 获取回调函数的执行结果
let result = type(this.PromiseResult);
// 判断result为promise对象
if (result instanceof myPromise) {
result.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
// result为非promise对象,调用成功
// 结果的状态为成功
resolve(result);
}
} catch (e) {
reject(e);
}
};
// 调用回调函数
if (this.PromiseState === "fulfilled") {
setTimeout(() => {
callback(onResolved);
});
}
if (this.PromiseState === "rejected") {
setTimeout(() => {
callback(onRejected);
});
}
// 判断pending函数
if (this.PromiseState === "pending") {
// 保存回调函数
this.callbacks.push({
// 简写
onResolved: () => {
callback(onResolved);
},
onRejected: () => {
callback(onRejected);
},
});
}
});
}
// catch函数
catch(onRejected) {
return this.then(undefined, onRejected);
}
// resolve方法
static resolve(value) {
return new myPromise((resolve, reject) => {
if (value instanceof myPromise) {
value.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
resolve(value);
}
});
}
// // reject方法
static reject(reason) {
return new myPromise((resolve, reject) => {
reject(reason);
});
}
// all方法
static all(promise) {
return new myPromise((resolve, reject) => {
// 声明成功对象的个数
let count = 0;
// 声明成功结果的数组
let arr = [];
// 遍历
for (let i = 0; i < promise.length; i++) {
promise[i].then(
(v) => {
// 对象状态为成功
// 每个promise中都成功就调用resolve
count++;
arr[i] = v;
if (count === promise.length) {
resolve(arr);
}
},
(r) => {
reject(r);
}
);
}
});
}
// race方法
static race(promise) {
return new myPromise((resolve, reject) => {
for (let i = 0; i < promise.length; i++) {
promise[i].then(
(v) => {
// 修改返回对象的状态为成功
resolve(v);
},
(r) => {
// 修改返回对象的状态为失败
reject(r);
}
);
}
});
}
}