6、捕获错误及 then 链式调用其余状态代码补充编程
这里只是对Promise源码的实现作一个剖析,若是想对Promise总体有个了解,<br/>
请看 ES6(十一)—— Promise(更优的异步编程解决方案)
首先分析其原理segmentfault
promise
就是一个类<br/>在执行类的时候须要传递一个执行器进去,执行器会当即执行数组
Promise
中有三种状态,分别为成功-fulfilled
失败-rejected
等待-pending
<br/>pending -> fulfilled
<br/>pending -> rejected
<br/>
一旦状态肯定就不可更改resolve
和reject
函数是用来更改状态的<br/>
resolve:fulfilled
<br/>reject:rejected
promise
then
方法内部作的事情就是判断状态若是状态是成功,调用成功回调函数<br/>
若是状态是失败,就调用失败回调函数<br/>then
方法是被定义在原型对象中的并发
then
成功回调有一个参数,表示成功以后的值;then
失败回调有一个参数,表示失败后的缘由
<PS:本文myPromise.js是源码文件,promise.js是使用promise文件>异步
// myPromise.js // 定义成常量是为了复用且代码有提示 const PENDING = 'pending' // 等待 const FULFILLED = 'fulfilled' // 成功 const REJECTED = 'rejected' // 失败 // 定义一个构造函数 class MyPromise { constructor (exector) { // exector是一个执行器,进入会当即执行,并传入resolve和reject方法 exector(this.resolve, this.reject) } // 实例对象的一个属性,初始为等待 status = PENDING // 成功以后的值 value = undefined // 失败以后的缘由 reason = undefined // resolve和reject为何要用箭头函数? // 若是直接调用的话,普通函数this指向的是window或者undefined // 用箭头函数就可让this指向当前实例对象 resolve = value => { // 判断状态是否是等待,阻止程序向下执行 if(this.status !== PENDING) return // 将状态改为成功 this.status = FULFILLED // 保存成功以后的值 this.value = value } reject = reason => { if(this.status !== PENDING) return // 将状态改成失败 this.status = REJECTED // 保存失败以后的缘由 this.reason = reason } then (successCallback, failCallback) { //判断状态 if(this.status === FULFILLED) { // 调用成功回调,而且把值返回 successCallback(this.value) } else if (this.status === REJECTED) { // 调用失败回调,而且把缘由返回 failCallback(this.reason) } } } module.exports = MyPromise
//promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { resolve('success') reject('err') }) promise.then(value => { console.log('resolve', value) }, reason => { console.log('reject', reason) })
上面是没有通过异步处理的,若是有异步逻辑加进来,会有一些问题异步编程
//promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { // 主线程代码当即执行,setTimeout是异步代码,then会立刻执行, // 这个时候判断promise状态,状态是pending,然而以前并无判断等待这个状态 setTimeout(() => { resolve('success') }, 2000); }) promise.then(value => { console.log('resolve', value) }, reason => { console.log('reject', reason) })
下面修改这个代码函数
// myPromise.js const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class MyPromise { constructor (exector) { exector(this.resolve, this.reject) } status = PENDING value = undefined reason = undefined // 定义一个成功回调参数 successCallback = undefined // 定义一个失败回调参数 failCallback = undefined resolve = value => { if(this.status !== PENDING) return this.status = FULFILLED this.value = value // 判断成功回调是否存在,若是存在就调用 this.successCallback && this.successCallback(this.value) } reject = reason => { if(this.status !== PENDING) return this.status = REJECTED this.reason = reason // 判断失败回调是否存在,若是存在就调用 this.failCallback && this.failCallback(this.reason) } then (successCallback, failCallback) { if(this.status === FULFILLED) { successCallback(this.value) } else if (this.status === REJECTED) { failCallback(this.reason) } else { // 等待 // 由于并不知道状态,因此将成功回调和失败回调存储起来 // 等到执行成功失败函数的时候再传递 this.successCallback = successCallback this.failCallback = failCallback } } } module.exports = MyPromise
promise
的then
方法是能够被屡次调用的。ui
这里若是有三个then
的调用,this
以前的代码须要改进。
//promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { setTimeout(() => { resolve('success') }, 2000); }) promise.then(value => { console.log(1) console.log('resolve', value) }) promise.then(value => { console.log(2) console.log('resolve', value) }) promise.then(value => { console.log(3) console.log('resolve', value) })
保存到数组中,最后统一执行
// myPromise.js const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class MyPromise { constructor (exector) { exector(this.resolve, this.reject) } status = PENDING value = undefined reason = undefined // 定义一个成功回调参数,初始化一个空数组 successCallback = [] // 定义一个失败回调参数,初始化一个空数组 failCallback = [] resolve = value => { if(this.status !== PENDING) return this.status = FULFILLED this.value = value // 判断成功回调是否存在,若是存在就调用 // 循环回调数组. 把数组前面的方法弹出来而且直接调用 // shift方法是在数组中删除值,每执行一个就删除一个,最终变为0 while(this.successCallback.length) this.successCallback.shift()(this.value) } reject = reason => { if(this.status !== PENDING) return this.status = REJECTED this.reason = reason // 判断失败回调是否存在,若是存在就调用 // 循环回调数组. 把数组前面的方法弹出来而且直接调用 while(this.failCallback.length) this.failCallback.shift()(this.reason) } then (successCallback, failCallback) { if(this.status === FULFILLED) { successCallback(this.value) } else if (this.status === REJECTED) { failCallback(this.reason) } else { // 等待 // 将成功回调和失败回调都保存在数组中 this.successCallback.push(successCallback) this.failCallback.push(failCallback) } } } module.exports = MyPromise
then
方法要链式调用那么就须要返回一个promise
对象,then
方法的return
返回值做为下一个then
方法的参数then
方法还一个return
一个promise
对象,那么若是是一个promise
对象,那么就须要判断它的状态// promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { // 目前这里只处理同步的问题 resolve('success') }) function other () { return new MyPromise((resolve, reject) =>{ resolve('other') }) } promise.then(value => { console.log(1) console.log('resolve', value) return other() }).then(value => { console.log(2) console.log('resolve', value) })
// myPromise.js const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class MyPromise { constructor (exector) { exector(this.resolve, this.reject) } status = PENDING value = undefined reason = undefined successCallback = [] failCallback = [] resolve = value => { if(this.status !== PENDING) return this.status = FULFILLED this.value = value while(this.successCallback.length) this.successCallback.shift()(this.value) } reject = reason => { if(this.status !== PENDING) return this.status = REJECTED this.reason = reason while(this.failCallback.length) this.failCallback.shift()(this.reason) } then (successCallback, failCallback) { // then方法返回第一个promise对象 let promise2 = new Promise((resolve, reject) => { if(this.status === FULFILLED) { // x是上一个promise回调函数的return返回值 // 判断 x 的值时普通值仍是promise对象 // 若是是普通纸 直接调用resolve // 若是是promise对象 查看promise对象返回的结果 // 再根据promise对象返回的结果 决定调用resolve仍是reject let x = successCallback(this.value) resolvePromise(x, resolve, reject) } else if (this.status === REJECTED) { failCallback(this.reason) } else { this.successCallback.push(successCallback) this.failCallback.push(failCallback) } }); return promise2 } } function resolvePromise(x, resolve, reject) { // 判断x是否是其实例对象 if(x instanceof MyPromise) { // promise 对象 // x.then(value => resolve(value), reason => reject(reason)) // 简化以后 x.then(resolve, reject) } else{ // 普通值 resolve(x) } } module.exports = MyPromise
若是then
方法返回的是本身的promise
对象,则会发生promise
的嵌套,这个时候程序会报错
var promise = new Promise((resolve, reject) => { resolve(100) }) var p1 = promise.then(value => { console.log(value) return p1 }) // 100 // Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>
因此为了不这种状况,咱们须要改造一下then
方法
// myPromise.js const { rejects } = require("assert") const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class MyPromise { constructor (exector) { exector(this.resolve, this.reject) } status = PENDING value = undefined reason = undefined successCallback = [] failCallback = [] resolve = value => { if(this.status !== PENDING) return this.status = FULFILLED this.value = value while(this.successCallback.length) this.successCallback.shift()(this.value) } reject = reason => { if(this.status !== PENDING) return this.status = REJECTED this.reason = reason while(this.failCallback.length) this.failCallback.shift()(this.reason) } then (successCallback, failCallback) { let promise2 = new Promise((resolve, reject) => { if(this.status === FULFILLED) { // 由于new Promise须要执行完成以后才有promise2,同步代码中没有pormise2, // 因此这部分代码须要异步执行 setTimeout(() => { let x = successCallback(this.value) //须要判断then以后return的promise对象和原来的是否是同样的, //判断x和promise2是否相等,因此给resolvePromise中传递promise2过去 resolvePromise(promise2, x, resolve, reject) }, 0); } else if (this.status === REJECTED) { failCallback(this.reason) } else { this.successCallback.push(successCallback) this.failCallback.push(failCallback) } }); return promise2 } } function resolvePromise(promise2, x, resolve, reject) { // 若是相等了,说明return的是本身,抛出类型错误并返回 if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise #<Promise>')) } if(x instanceof MyPromise) { x.then(resolve, reject) } else{ resolve(x) } } module.exports = MyPromise
// promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { resolve('success') }) // 这个时候将promise定义一个p1,而后返回的时候返回p1这个promise let p1 = promise.then(value => { console.log(1) console.log('resolve', value) return p1 }) // 运行的时候会走reject p1.then(value => { console.log(2) console.log('resolve', value) }, reason => { console.log(3) console.log(reason.message) }) // 1 // resolve success // 3 // Chaining cycle detected for promise #<Promise>
目前咱们在Promise
类中没有进行任何处理,因此咱们须要捕获和处理错误。
捕获执行器中的代码,若是执行器中有代码错误,那么promise
的状态要弄成错误状态
// myPromise.js constructor (exector) { // 捕获错误,若是有错误就执行reject try { exector(this.resolve, this.reject) } catch (e) { this.reject(e) } }
// promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { // resolve('success') throw new Error('执行器错误') }) promise.then(value => { console.log(1) console.log('resolve', value) }, reason => { console.log(2) console.log(reason.message) }) //2 //执行器错误
// myPromise.js then (successCallback, failCallback) { let promise2 = new Promise((resolve, reject) => { if(this.status === FULFILLED) { setTimeout(() => { // 若是回调中报错的话就执行reject try { let x = successCallback(this.value) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0); } else if (this.status === REJECTED) { failCallback(this.reason) } else { this.successCallback.push(successCallback) this.failCallback.push(failCallback) } }); return promise2 }
// promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { resolve('success') // throw new Error('执行器错误') }) // 第一个then方法中的错误要在第二个then方法中捕获到 promise.then(value => { console.log(1) console.log('resolve', value) throw new Error('then error') }, reason => { console.log(2) console.log(reason.message) }).then(value => { console.log(3) console.log(value); }, reason => { console.log(4) console.log(reason.message) }) // 1 // resolve success // 4 // then error
// myPromise.js then (successCallback, failCallback) { let promise2 = new Promise((resolve, reject) => { if(this.status === FULFILLED) { setTimeout(() => { try { let x = successCallback(this.value) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) // 在状态是reject的时候对返回的promise进行处理 } else if (this.status === REJECTED) { setTimeout(() => { // 若是回调中报错的话就执行reject try { let x = failCallback(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) } else { this.successCallback.push(successCallback) this.failCallback.push(failCallback) } }); return promise2 }
//promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { // resolve('success') throw new Error('执行器错误') }) // 第一个then方法中的错误要在第二个then方法中捕获到 promise.then(value => { console.log(1) console.log('resolve', value) }, reason => { console.log(2) console.log(reason.message) return 100 }).then(value => { console.log(3) console.log(value); }, reason => { console.log(4) console.log(reason.message) }) // 2 // 执行器错误 // 3 // 100
仍是要处理一下若是promise
里面有异步的时候,then
的链式调用的问题。
// myPromise.js const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class MyPromise { constructor (exector) { // 捕获错误,若是有错误就执行reject try { exector(this.resolve, this.reject) } catch (e) { this.reject(e) } } status = PENDING value = undefined reason = undefined successCallback = [] failCallback = [] resolve = value => { if(this.status !== PENDING) return this.status = FULFILLED this.value = value // 异步回调传值 // 调用的时候不须要传值,由于下面push到里面的时候已经处理好了 while(this.successCallback.length) this.successCallback.shift()() } reject = reason => { if(this.status !== PENDING) return this.status = REJECTED this.reason = reason // 异步回调传值 // 调用的时候不须要传值,由于下面push到里面的时候已经处理好了 while(this.failCallback.length) this.failCallback.shift()() } then (successCallback, failCallback) { let promise2 = new Promise((resolve, reject) => { if(this.status === FULFILLED) { setTimeout(() => { // 若是回调中报错的话就执行reject try { let x = successCallback(this.value) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) } else if (this.status === REJECTED) { setTimeout(() => { // 若是回调中报错的话就执行reject try { let x = failCallback(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) } else { // 处理异步的成功错误状况 this.successCallback.push(() => { setTimeout(() => { // 若是回调中报错的话就执行reject try { let x = successCallback(this.value) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) }) this.failCallback.push(() => { setTimeout(() => { // 若是回调中报错的话就执行reject try { let x = failCallback(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) }) } }); return promise2 } } function resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise #<Promise>')) } if(x instanceof MyPromise) { x.then(resolve, reject) } else{ resolve(x) } } module.exports = MyPromise
// promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { // 一个异步方法 setTimeout(() =>{ resolve('succ') },2000) }) promise.then(value => { console.log(1) console.log('resolve', value) return 'aaa' }, reason => { console.log(2) console.log(reason.message) return 100 }).then(value => { console.log(3) console.log(value); }, reason => { console.log(4) console.log(reason.message) }) // 1 // resolve succ // 3 // aaa
then方法的两个参数都是可选参数,咱们能够不传参数。
下面的参数能够传递到最后进行返回
var promise = new Promise((resolve, reject) => { resolve(100) }) promise .then() .then() .then() .then(value => console.log(value)) // 在控制台最后一个then中输出了100 // 这个至关于 promise .then(value => value) .then(value => value) .then(value => value) .then(value => console.log(value))
因此咱们修改一下then
方法
// myPromise.js then (successCallback, failCallback) { // 这里进行判断,若是有回调就选择回调,若是没有回调就传一个函数,把参数传递 successCallback = successCallback ? successCallback : value => value // 错误函数也是进行赋值,把错误信息抛出 failCallback = failCallback ? failCallback : reason => {throw reason} let promise2 = new Promise((resolve, reject) => { ... }) ... } // 简化也能够这样写 then (successCallback = value => value, failCallback = reason => {throw reason}) { ··· }
resolve
以后
// promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { resolve('succ') }) promise.then().then().then(value => console.log(value)) // succ
reject
以后
// promise.js const MyPromise = require('./myPromise') let promise = new MyPromise((resolve, reject) => { reject('err') }) promise.then().then().then(value => console.log(value), reason => console.log(reason)) // err
promise.all
方法是解决异步并发问题的
// 若是p1是两秒以后执行的,p2是当即执行的,那么根据正常的是p2在p1的前面。 // 若是咱们在all中指定了执行顺序,那么会根据咱们传递的顺序进行执行。 function p1 () { return new Promise((resolve, reject) => { setTimeout(() => { resolve('p1') }, 2000) }) } function p2 () { return new Promise((resolve, reject) => { setTimeout(() => { resolve('p2') },0) }) } Promise.all(['a', 'b', p1(), p2(), 'c']).then(result => { console.log(result) // ["a", "b", "p1", "p2", "c"] })
分析一下:
all
方法接收一个数组,数组中能够是普通值也能够是promise
对象promise
返回值也是一个promise
对象,能够调用then
方法then
里面就是成功回调,若是有一个值是失败的,那么then
里面就是失败的all
方法是用类直接调用,那么all
必定是一个静态方法//myPromise.js static all (array) { // 结果数组 let result = [] // 计数器 let index = 0 return new Promise((resolve, reject) => { let addData = (key, value) => { result[key] = value index ++ // 若是计数器和数组长度相同,那说明全部的元素都执行完毕了,就能够输出了 if(index === array.length) { resolve(result) } } // 对传递的数组进行遍历 for (let i = 0; i < array.lengt; i++) { let current = array[i] if (current instanceof MyPromise) { // promise对象就执行then,若是是resolve就把值添加到数组中去,若是是错误就执行reject返回 current.then(value => addData(i, value), reason => reject(reason)) } else { // 普通值就加到对应的数组中去 addData(i, array[i]) } } }) }
// promise.js const MyPromise = require('./myPromise') function p1 () { return new MyPromise((resolve, reject) => { setTimeout(() => { resolve('p1') }, 2000) }) } function p2 () { return new MyPromise((resolve, reject) => { setTimeout(() => { resolve('p2') },0) }) } Promise.all(['a', 'b', p1(), p2(), 'c']).then(result => { console.log(result) // ["a", "b", "p1", "p2", "c"] })
promise
对象,直接返回,若是是一个值,那么须要生成一个promise
对象,把值进行返回Promise
类的一个静态方法// myPromise.js static resolve (value) { // 若是是promise对象,就直接返回 if(value instanceof MyPromise) return value // 若是是值就返回一个promise对象,并返回值 return new MyPromise(resolve => resolve(value)) }
// promise.js const MyPromise = require('./myPromise') function p1 () { return new MyPromise((resolve, reject) => { setTimeout(() => { resolve('p1') }, 2000) }) } Promise.resolve(100).then(value => console.log(value)) Promise.resolve(p1()).then(value => console.log(value)) // 100 // 2s 以后输出 p1
finally
都会执行finally
方法以后调用then
方法拿到结果// myPromise.js finally (callback) { // 如何拿到当前的promise的状态,使用then方法,并且无论怎样都返回callback // 并且then方法就是返回一个promise对象,那么咱们直接返回then方法调用以后的结果便可 // 咱们须要在回调以后拿到成功的回调,因此须要把value也return // 失败的回调也抛出缘由 // 若是callback是一个异步的promise对象,咱们还须要等待其执行完毕,因此须要用到静态方法resolve return this.then(value => { // 把callback调用以后返回的promise传递过去,而且执行promise,且在成功以后返回value return MyPromise.resolve(callback()).then(() => value) }, reason => { // 失败以后调用的then方法,而后把失败的缘由返回出去。 return MyPromise.resolve(callback()).then(() => { throw reason }) }) }
// promise.js const MyPromise = require('./myPromise') function p1 () { return new MyPromise((resolve, reject) => { setTimeout(() => { resolve('p1') }, 2000) }) } function p2 () { return new MyPromise((resolve, reject) => { reject('p2 reject') }) } p2().finally(() => { console.log('finallyp2') return p1() }).then(value => { console.log(value) }, reason => { console.log(reason) }) // finallyp2 // 两秒以后执行p2 reject
catch
方法是为了捕获promise
对象的全部错误回调的then
方法,而后成功的地方传递undefined
,错误的地方传递reason
catch
方法是做用在原型对象上的方法// myPromise.js catch (failCallback) { return this.then(undefined, failCallback) }
// promise.js const MyPromise = require('./myPromise') function p2 () { return new MyPromise((resolve, reject) => { reject('p2 reject') }) } p2() .then(value => { console.log(value) }) .catch(reason => console.log(reason)) // p2 reject
// myPromise.js const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected' class MyPromise { constructor (exector) { try { exector(this.resolve, this.reject) } catch (e) { this.reject(e) } } status = PENDING value = undefined reason = undefined successCallback = [] failCallback = [] resolve = value => { if(this.status !== PENDING) return this.status = FULFILLED this.value = value while(this.successCallback.length) this.successCallback.shift()() } reject = reason => { if(this.status !== PENDING) return this.status = REJECTED this.reason = reason while(this.failCallback.length) this.failCallback.shift()() } then (successCallback = value => value, failCallback = reason => {throw reason}) { let promise2 = new Promise((resolve, reject) => { if(this.status === FULFILLED) { setTimeout(() => { try { let x = successCallback(this.value) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) } else if (this.status === REJECTED) { setTimeout(() => { try { let x = failCallback(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) } else { this.successCallback.push(() => { setTimeout(() => { try { let x = successCallback(this.value) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) }) this.failCallback.push(() => { setTimeout(() => { try { let x = failCallback(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (e) { reject(e) } }, 0) }) } }); return promise2 } finally (callback) { // 如何拿到当前的promise的状态,使用then方法,并且无论怎样都返回callback // 并且then方法就是返回一个promise对象,那么咱们直接返回then方法调用以后的结果便可 // 咱们须要在回调以后拿到成功的回调,因此须要把value也return // 失败的回调也抛出缘由 // 若是callback是一个异步的promise对象,咱们还须要等待其执行完毕,因此须要用到静态方法resolve return this.then(value => { // 把callback调用以后返回的promise传递过去,而且执行promise,且在成功以后返回value return MyPromise.resolve(callback()).then(() => value) }, reason => { // 失败以后调用的then方法,而后把失败的缘由返回出去。 return MyPromise.resolve(callback()).then(() => { throw reason }) }) } catch (failCallback) { return this.then(undefined, failCallback) } static all (array) { let result = [] let index = 0 return new Promise((resolve, reject) => { let addData = (key, value) => { result[key] = value index ++ if(index === array.length) { resolve(result) } } for (let i = 0; i < array.lengt; i++) { let current = array[i] if (current instanceof MyPromise) { current.then(value => addData(i, value), reason => reject(reason)) } else { addData(i, array[i]) } } }) } static resolve (value) { if(value instanceof MyPromise) return value return new MyPromise(resolve => resolve(value)) } } function resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise #<Promise>')) } if(x instanceof MyPromise) { x.then(resolve, reject) } else{ resolve(x) } } module.exports = MyPromise