├── name.txt ├── README.md ├── after.js ├── base.js ├── all.js ├── watch.js ├── alltest.js ├── base1.js ├── hocFunction.js ├── promise1.js ├── file.js ├── promisethen.js ├── promisecallback.js ├── promiseresolve.js └── promise.js /name.txt: -------------------------------------------------------------------------------- 1 | '张三' -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # promise 2 | 自己实现promise 3 | 4 | 5 | 分步骤 6 | 7 | promise1.js 同步promise 8 | 9 | promisethen 实现promise then方法 10 | 11 | promisecallback 实现promise then无限回调 12 | 13 | promiseresolve 实现promise resolve 方法 14 | 15 | promise 实现promise all方法 16 | -------------------------------------------------------------------------------- /after.js: -------------------------------------------------------------------------------- 1 | // after 在...之后 2 | 3 | // 在某个时机之后再执行 4 | function after(times, say) { // 高阶函数 5 | return function() { 6 | if(--times === 0) { 7 | say() 8 | } 9 | } 10 | } 11 | 12 | 13 | let hello = after(3, function say(){ 14 | console.log('say hello') 15 | }) 16 | 17 | hello() 18 | hello() 19 | hello() -------------------------------------------------------------------------------- /base.js: -------------------------------------------------------------------------------- 1 | // 什么是promise (基于回调) 2 | // 1.回调地狱 3 | // 2.多个请求并发问题 4 | 5 | // promise 是一个类 new promise 6 | // 有三个状态 pending fulfilled rejected 7 | // promise是等待态 默认提供两个函数 resolve变成成功 reject失败 8 | // 抛出错误,变成reject 9 | // 多次调用成功或者失败,只会执行第一次 10 | 11 | let MyPromise = require('./promise') 12 | let promise = new MyPromise((resolve, reject) => { 13 | // throw new Error('error') 14 | // reject('faild') 15 | setTimeout(()=>{ 16 | 17 | resolve('success') 18 | }) 19 | }) 20 | 21 | promise.then((res) => { 22 | console.log(res) 23 | }) -------------------------------------------------------------------------------- /all.js: -------------------------------------------------------------------------------- 1 | // Promise.all 2 | 3 | const fs = require('fs') 4 | 5 | // 异步方法 6 | // let obj = {} 7 | // fs.readFile('./name.txt', 'utf8', function(err, data){ 8 | // obj.name = data 9 | // console.log('hello', data) 10 | // }) 11 | 12 | // 并不能获取到数据 13 | // console.log(obj) 14 | 15 | const after = (times, fn) => () => --times === 0 && fn() 16 | 17 | const outer = after(1, () => { 18 | console.log(obj) 19 | }) 20 | 21 | let obj = {} 22 | fs.readFile('./name.txt', 'utf8', function(err, data){ 23 | obj.name = data 24 | console.log('hello', data) 25 | outer() 26 | }) -------------------------------------------------------------------------------- /watch.js: -------------------------------------------------------------------------------- 1 | // 发布订阅 是发布和订阅之间没有任何联系 2 | // 观察者模式 (内部是基于发布订阅的) 有一个观察者 被观察者 3 | 4 | class Subject { 5 | constructor(name){ 6 | this.name = name 7 | this.arr = [] 8 | this.status = 'happy' 9 | } 10 | attach(observer){ // 注册观察者 基于发布订阅 11 | this.arr.push(observer) 12 | } 13 | setStatus(status){ 14 | this.status = status 15 | this.arr.forEach(o => o.update(status)) 16 | } 17 | } 18 | 19 | class Observer { // 观察者 20 | constructor(name){ 21 | this.name = name 22 | } 23 | update(status){ 24 | console.log(status) 25 | } 26 | } 27 | 28 | let s = new Subject('baby') 29 | let m1 = new Observer('father') 30 | let m2 = new Observer('mother') 31 | 32 | // 注册关系 33 | s.attach(m1) 34 | s.attach(m2) 35 | 36 | // 状态改变通知观察者 37 | s.setStatus('cry') -------------------------------------------------------------------------------- /alltest.js: -------------------------------------------------------------------------------- 1 | let fs = require('fs') 2 | let MyPromise = require('./promise') 3 | // let util = require('util') 4 | 5 | // let read = util.promisify(fs.readFile) 6 | 7 | // 高阶函数 参数是函数 返回值是函数 8 | function promisify(fn){ 9 | return function(...args){ 10 | return new MyPromise((reslove, reject) => { 11 | fn(...args, function(err, data){ 12 | if (err) reject() 13 | reslove(data) 14 | }) 15 | }) 16 | } 17 | } 18 | 19 | // let read = promisify(fs.readFile) 20 | 21 | // read('name.txt', 'utf8').then(data => { 22 | // console.log(data) 23 | // }) 24 | 25 | 26 | let fs1 = require('fs').promises 27 | // Promise.all([1,2,3,fs1.readFile('name.txt', 'utf8')]).then(value => { 28 | // console.log(value) 29 | // }) 30 | 31 | MyPromise.all([1,2,3,fs1.readFile('name3.txt', 'utf8')]).then(value => { 32 | console.log(value) 33 | }, err => { 34 | console.log(666, err) 35 | }) -------------------------------------------------------------------------------- /base1.js: -------------------------------------------------------------------------------- 1 | let fs = require('fs') 2 | 3 | let MyPromise = require('./promise') 4 | 5 | function read1() { 6 | return new MyPromise((resolve, reject) => { 7 | fs.readFile('name.txt', 'utf8', function(err, data) { 8 | if (err) { 9 | reject(err) 10 | } 11 | resolve(data) 12 | }) 13 | }) 14 | } 15 | 16 | function read() { 17 | let dfd = MyPromise.deferred() 18 | 19 | fs.readFile('name.txt', 'utf8', function(err, data) { 20 | if (err) { 21 | dfd.reject(err) 22 | } 23 | dfd.resolve(data) 24 | }) 25 | return dfd.promise 26 | } 27 | 28 | // read1().then(data => { 29 | // console.log(1, data) 30 | // }) 31 | // read1().catch(data => { 32 | // console.log('err', data) 33 | // }) 34 | // read().then(data => { 35 | // console.log(data) 36 | // }) 37 | 38 | 39 | let p = new MyPromise((resolve, reject) => { 40 | resolve('88') 41 | }) 42 | // resolve方法 43 | let p2 = new MyPromise((resolve, reject) => { 44 | resolve(new MyPromise((resolve, reject) => { 45 | resolve('888') 46 | })) 47 | }) 48 | 49 | p.then(res => { 50 | console.log(res) 51 | }) 52 | p2.then(res => { 53 | console.log(res) 54 | }) 55 | 56 | 57 | -------------------------------------------------------------------------------- /hocFunction.js: -------------------------------------------------------------------------------- 1 | // 高阶函数 一个函数的参数是另一个函数 回调函数 (函数柯里化) 2 | 3 | // function say(callback) { 4 | // return () => { 5 | // callback() 6 | // } 7 | // } 8 | 9 | // say(function(){ 10 | // console.log(9999) 11 | // })() 12 | 13 | // 函数柯里化 14 | // 判断一个变量的类型 15 | // function checkType (value, type) { 16 | // return Object.prototype.toString.call(value) === `[object ${type}]` 17 | // } 18 | 19 | // console.log(checkType('name', 'String')) 20 | 21 | // 把一个函数的范围进行缩小,让函数变得更具体 22 | function checkType(type){ 23 | return function(value) { 24 | return Object.prototype.toString.call(value) === `[object ${type}]` 25 | } 26 | } 27 | 28 | const isString = checkType('String') 29 | const isBoolean = checkType('Boolean') 30 | 31 | const f1 = isString('name') 32 | const f2 = isBoolean(true) 33 | const f3 = isBoolean('aaa') 34 | console.log(f1, f2, f3) 35 | 36 | // 柯里化一定会导致闭包 37 | 38 | // 实现通用的函数柯里化 39 | const add = (a, b, c, d) => { 40 | return a+b+c+d 41 | } 42 | 43 | const curring = (fn, arr=[]) => { 44 | let len = fn.length 45 | return (...args) => { 46 | arr = arr.concat(args) 47 | if (arr.length < len) { 48 | return curring(fn, arr) 49 | } 50 | return fn(...arr) 51 | } 52 | } 53 | 54 | console.log(curring(add, [7])(1,2)(4)) 55 | 56 | // 函数反柯里化 让一个函数的范围变大 57 | -------------------------------------------------------------------------------- /promise1.js: -------------------------------------------------------------------------------- 1 | const PENDING = 'pending' // 等待 2 | const FULFILLED = 'fulfilled' // 成功 3 | const REJECTED = 'rejected' // 失败 4 | 5 | class MyPromise { 6 | constructor(executor){ 7 | this.state = PENDING 8 | this.value = undefined 9 | this.reason = undefined 10 | this.onResolvedCallbacks = [] // 存放成功时的回调 11 | this.onRejectedCallbacks = [] // 存放失败时的回调 12 | let resolve = (value) =>{ 13 | if (this.state === PENDING) { 14 | this.state = FULFILLED 15 | this.value = value 16 | this.onResolvedCallbacks.forEach(fn => fn()) 17 | } 18 | } 19 | let reject = (reason) => { 20 | if (this.state === PENDING) { 21 | this.state = REJECTED 22 | this.reason = reason 23 | this.onRejectedCallbacks.forEach(fn => fn()) 24 | } 25 | } 26 | try { 27 | 28 | executor(resolve, reject) 29 | } catch (error) { 30 | reject(error) 31 | } 32 | } 33 | then(onfulfilled, onRejected){ 34 | if (this.state === FULFILLED) { 35 | onfulfilled(this.value) 36 | } 37 | if (this.state === REJECTED) { 38 | onfulfilled(this.reason) 39 | } 40 | if (this.state === PENDING) { 41 | console.log(99) 42 | this.onResolvedCallbacks.push(()=>{ 43 | onfulfilled(this.value) 44 | }) 45 | this.onRejectedCallbacks.push(() => { 46 | onfulfilled(this.reason) 47 | }) 48 | } 49 | } 50 | } 51 | 52 | module.exports = MyPromise -------------------------------------------------------------------------------- /file.js: -------------------------------------------------------------------------------- 1 | let MyPromise = require('./promise') 2 | let fs = require('fs') 3 | 4 | function read(...args) { 5 | return new Promise((resolve, reject) => { 6 | fs.readFile(...args, function(err, data){ 7 | if (err) { 8 | reject(err) 9 | } 10 | resolve(data) 11 | }) 12 | }) 13 | } 14 | 15 | read('name.txt', 'utf8').then((data) => { 16 | // console.log(data) 17 | return read('name.txt', 'utf8') 18 | }).catch(()=>{ 19 | return 100 20 | }) 21 | let promise = new MyPromise((resolve, reject) => { 22 | resolve('888') 23 | }) 24 | let promise2 = promise.then(data => { 25 | // return data 26 | // throw new Error('error') 27 | // return promise2 28 | return new MyPromise((resolve, reject) => { 29 | resolve('9999') 30 | // reject('777') 31 | // resolve(new MyPromise((resolve,reject) => { 32 | // setTimeout(()=>{ 33 | // resolve('hello') 34 | // }, 1000) 35 | // })) 36 | 37 | }) 38 | }) 39 | // promise2.then(data =>{ 40 | // console.log(6,data) 41 | // }, error => { 42 | // console.log(error) 43 | // }) 44 | 45 | // .then(data =>{ 46 | // console.log(2,data) 47 | // }, err => { 48 | // return 100 49 | // }) 50 | // .then(res => { 51 | // console.log(3, res) 52 | // throw new Error('44') 53 | // }).catch((err) => { 54 | // console.log(4, err) 55 | // }) 56 | 57 | let p = promise2.then(data =>{ 58 | console.log(6,data) 59 | return new MyPromise((resolve, reject) => { 60 | resolve(data) 61 | }) 62 | }, error => { 63 | console.log(error) 64 | }) 65 | p.then().then().then().then(res => { 66 | console.log(10, res) 67 | }) -------------------------------------------------------------------------------- /promisethen.js: -------------------------------------------------------------------------------- 1 | // promise then方法 2 | const PENDING = 'pending' // 等待 3 | const FULFILLED = 'fulfilled' // 成功 4 | const REJECTED = 'rejected' // 失败 5 | 6 | const resolvePromise = (promise2, x, resolve, reject) => { 7 | if (promise2 === x) { // 不能返回自己,死循环,直接抛出错误 8 | return reject(new TypeError('类型错误')) 9 | } 10 | // 判断x的状态 判断x是不是promise 11 | // 1.判断是不是对象或者函数 12 | if (typeof x === 'object' && x !== null || typeof x === 'function'){ 13 | // x需要是一个对象或者函数 14 | let called // 只能掉一个方法,失败或者成功,不能多吃调用成功或失败 15 | try { 16 | let then = x.then // 取出then方法 这个方法是采用defineProperty来定义的 17 | if (typeof then === 'function') { // 如果then不是一个函数,说明不是promise 18 | then.call(x, y => { // 将then作为this 19 | // resolve(y) // 如果是promise继续调用 20 | // console.log(99999) 21 | if (called) return 22 | called = true 23 | resolvePromise(promise2, y, resolve, reject) 24 | },r=>{ 25 | if (called) return 26 | called = true 27 | reject(r) 28 | }) 29 | } else { 30 | if (called) return 31 | called = true 32 | resolve(x) 33 | } 34 | } catch (error) { 35 | if (called) return 36 | called = true 37 | reject(error) 38 | } 39 | }else { 40 | resolve(x) 41 | } 42 | 43 | } 44 | class MyPromise { 45 | constructor(executor){ 46 | this.state = PENDING 47 | this.value = undefined 48 | this.reason = undefined 49 | this.onResolvedCallbacks = [] // 存放成功时的回调 50 | this.onRejectedCallbacks = [] // 存放失败时的回调 51 | let resolve = (value) =>{ 52 | if (this.state === PENDING) { 53 | this.state = FULFILLED 54 | this.value = value 55 | this.onResolvedCallbacks.forEach(fn => fn()) 56 | } 57 | } 58 | let reject = (reason) => { 59 | if (this.state === PENDING) { 60 | this.state = REJECTED 61 | this.reason = reason 62 | this.onRejectedCallbacks.forEach(fn => fn()) 63 | } 64 | } 65 | try { // 只能捕获同步异常 66 | 67 | executor(resolve, reject) 68 | } catch (error) { 69 | reject(error) 70 | } 71 | } 72 | then(onfulfilled, onRejected){ 73 | // 递归 74 | let promise2 = new MyPromise((resolve, reject) => { 75 | if (this.state === FULFILLED) { 76 | setTimeout(() => { 77 | try { 78 | 79 | let x = onfulfilled(this.value) 80 | resolvePromise(promise2, x, resolve, reject) 81 | } catch (error) { 82 | reject(error) 83 | } 84 | }, 0) 85 | } 86 | if (this.state === REJECTED) { 87 | setTimeout(() => { 88 | try { 89 | let x = onRejected(this.reason) 90 | resolvePromise(promise2, x, resolve, reject) 91 | 92 | }catch(e){ 93 | reject(e) 94 | } 95 | }, 0) 96 | } 97 | if (this.state === PENDING) { 98 | // console.log(99) 99 | this.onResolvedCallbacks.push(()=>{ 100 | setTimeout(() => { 101 | try { 102 | let x = onfulfilled(this.value) 103 | resolvePromise(promise2, x, resolve, reject) 104 | } catch (error) { 105 | reject(error) 106 | } 107 | }, 0) 108 | }) 109 | this.onRejectedCallbacks.push(() => { 110 | setTimeout(() => { 111 | try { 112 | let x = onRejected(this.reason) 113 | resolvePromise(promise2, x, resolve, reject) 114 | 115 | } catch (error) { 116 | reject(error) 117 | } 118 | }, 0) 119 | }) 120 | 121 | } 122 | 123 | }) 124 | return promise2 125 | } 126 | } 127 | 128 | module.exports = MyPromise -------------------------------------------------------------------------------- /promisecallback.js: -------------------------------------------------------------------------------- 1 | // promise then方法 then无限调用 2 | const PENDING = 'pending' // 等待 3 | const FULFILLED = 'fulfilled' // 成功 4 | const REJECTED = 'rejected' // 失败 5 | 6 | const resolvePromise = (promise2, x, resolve, reject) => { 7 | if (promise2 === x) { // 不能返回自己,死循环,直接抛出错误 8 | return reject(new TypeError('类型错误')) 9 | } 10 | // 判断x的状态 判断x是不是promise 11 | // 1.判断是不是对象或者函数 12 | if (typeof x === 'object' && x !== null || typeof x === 'function'){ 13 | // x需要是一个对象或者函数 14 | let called // 只能掉一个方法,失败或者成功,不能多吃调用成功或失败 15 | try { 16 | let then = x.then // 取出then方法 这个方法是采用defineProperty来定义的 17 | if (typeof then === 'function') { // 如果then不是一个函数,说明不是promise 18 | then.call(x, y => { // 将then作为this 19 | // resolve(y) // 如果是promise继续调用 20 | // console.log(99999) 21 | if (called) return 22 | called = true 23 | resolvePromise(promise2, y, resolve, reject) 24 | },r=>{ 25 | if (called) return 26 | called = true 27 | reject(r) 28 | }) 29 | } else { 30 | if (called) return 31 | called = true 32 | resolve(x) 33 | } 34 | } catch (error) { 35 | if (called) return 36 | called = true 37 | reject(error) 38 | } 39 | }else { 40 | resolve(x) 41 | } 42 | 43 | } 44 | class MyPromise { 45 | constructor(executor){ 46 | this.state = PENDING 47 | this.value = undefined 48 | this.reason = undefined 49 | this.onResolvedCallbacks = [] // 存放成功时的回调 50 | this.onRejectedCallbacks = [] // 存放失败时的回调 51 | let resolve = (value) =>{ 52 | if (this.state === PENDING) { 53 | this.state = FULFILLED 54 | this.value = value 55 | this.onResolvedCallbacks.forEach(fn => fn()) 56 | } 57 | } 58 | let reject = (reason) => { 59 | if (this.state === PENDING) { 60 | this.state = REJECTED 61 | this.reason = reason 62 | this.onRejectedCallbacks.forEach(fn => fn()) 63 | } 64 | } 65 | try { // 只能捕获同步异常 66 | 67 | executor(resolve, reject) 68 | } catch (error) { 69 | reject(error) 70 | } 71 | } 72 | then(onfulfilled, onRejected){ 73 | // 可选参数处理 参数穿透 多次调用then 74 | onfulfilled = typeof onfulfilled === 'function'? 75 | onfulfilled: val => val 76 | onRejected = typeof onRejected === 'function'? 77 | onRejected: err => {throw err} 78 | // 递归 79 | let promise2 = new MyPromise((resolve, reject) => { 80 | if (this.state === FULFILLED) { 81 | setTimeout(() => { 82 | try { 83 | 84 | let x = onfulfilled(this.value) 85 | resolvePromise(promise2, x, resolve, reject) 86 | } catch (error) { 87 | reject(error) 88 | } 89 | }, 0) 90 | } 91 | if (this.state === REJECTED) { 92 | setTimeout(() => { 93 | try { 94 | let x = onRejected(this.reason) 95 | resolvePromise(promise2, x, resolve, reject) 96 | 97 | }catch(e){ 98 | reject(e) 99 | } 100 | }, 0) 101 | } 102 | if (this.state === PENDING) { 103 | // console.log(99) 104 | this.onResolvedCallbacks.push(()=>{ 105 | setTimeout(() => { 106 | try { 107 | let x = onfulfilled(this.value) 108 | resolvePromise(promise2, x, resolve, reject) 109 | } catch (error) { 110 | reject(error) 111 | } 112 | }, 0) 113 | }) 114 | this.onRejectedCallbacks.push(() => { 115 | setTimeout(() => { 116 | try { 117 | let x = onRejected(this.reason) 118 | resolvePromise(promise2, x, resolve, reject) 119 | 120 | } catch (error) { 121 | reject(error) 122 | } 123 | }, 0) 124 | }) 125 | 126 | } 127 | 128 | }) 129 | return promise2 130 | } 131 | 132 | } 133 | 134 | // 静态方法 135 | MyPromise.deferred = function () { 136 | let dfd = {} 137 | dfd.promise = new MyPromise((resolve, reject) => { 138 | dfd.resolve = resolve 139 | dfd.reject = reject 140 | }) 141 | return dfd 142 | } 143 | 144 | module.exports = MyPromise -------------------------------------------------------------------------------- /promiseresolve.js: -------------------------------------------------------------------------------- 1 | // promise then方法 then无限调用 2 | const PENDING = 'pending' // 等待 3 | const FULFILLED = 'fulfilled' // 成功 4 | const REJECTED = 'rejected' // 失败 5 | 6 | const resolvePromise = (promise2, x, resolve, reject) => { 7 | if (promise2 === x) { // 不能返回自己,死循环,直接抛出错误 8 | return reject(new TypeError('类型错误')) 9 | } 10 | // 判断x的状态 判断x是不是promise 11 | // 1.判断是不是对象或者函数 12 | if (typeof x === 'object' && x !== null || typeof x === 'function'){ 13 | // x需要是一个对象或者函数 14 | let called // 只能掉一个方法,失败或者成功,不能多吃调用成功或失败 15 | try { 16 | let then = x.then // 取出then方法 这个方法是采用defineProperty来定义的 17 | if (typeof then === 'function') { // 如果then不是一个函数,说明不是promise 18 | then.call(x, y => { // 将then作为this 19 | // resolve(y) // 如果是promise继续调用 20 | // console.log(99999) 21 | if (called) return 22 | called = true 23 | resolvePromise(promise2, y, resolve, reject) 24 | },r=>{ 25 | if (called) return 26 | called = true 27 | reject(r) 28 | }) 29 | } else { 30 | if (called) return 31 | called = true 32 | resolve(x) 33 | } 34 | } catch (error) { 35 | if (called) return 36 | called = true 37 | reject(error) 38 | } 39 | }else { 40 | resolve(x) 41 | } 42 | 43 | } 44 | class MyPromise { 45 | constructor(executor){ 46 | this.state = PENDING 47 | this.value = undefined 48 | this.reason = undefined 49 | this.onResolvedCallbacks = [] // 存放成功时的回调 50 | this.onRejectedCallbacks = [] // 存放失败时的回调 51 | let resolve = (value) =>{ 52 | if (value instanceof MyPromise) { 53 | return value.then(resolve, reject) 54 | } 55 | if (this.state === PENDING) { 56 | this.state = FULFILLED 57 | this.value = value 58 | this.onResolvedCallbacks.forEach(fn => fn()) 59 | } 60 | } 61 | let reject = (reason) => { 62 | if (this.state === PENDING) { 63 | this.state = REJECTED 64 | this.reason = reason 65 | this.onRejectedCallbacks.forEach(fn => fn()) 66 | } 67 | } 68 | try { // 只能捕获同步异常 69 | 70 | executor(resolve, reject) 71 | } catch (error) { 72 | reject(error) 73 | } 74 | } 75 | then(onfulfilled, onRejected){ 76 | // 可选参数处理 参数穿透 多次调用then 77 | onfulfilled = typeof onfulfilled === 'function'? 78 | onfulfilled: val => val 79 | onRejected = typeof onRejected === 'function'? 80 | onRejected: err => {throw err} 81 | // 递归 82 | let promise2 = new MyPromise((resolve, reject) => { 83 | if (this.state === FULFILLED) { 84 | setTimeout(() => { 85 | try { 86 | 87 | let x = onfulfilled(this.value) 88 | resolvePromise(promise2, x, resolve, reject) 89 | } catch (error) { 90 | reject(error) 91 | } 92 | }, 0) 93 | } 94 | if (this.state === REJECTED) { 95 | setTimeout(() => { 96 | try { 97 | let x = onRejected(this.reason) 98 | resolvePromise(promise2, x, resolve, reject) 99 | 100 | }catch(e){ 101 | reject(e) 102 | } 103 | }, 0) 104 | } 105 | if (this.state === PENDING) { 106 | // console.log(99) 107 | this.onResolvedCallbacks.push(()=>{ 108 | setTimeout(() => { 109 | try { 110 | let x = onfulfilled(this.value) 111 | resolvePromise(promise2, x, resolve, reject) 112 | } catch (error) { 113 | reject(error) 114 | } 115 | }, 0) 116 | }) 117 | this.onRejectedCallbacks.push(() => { 118 | setTimeout(() => { 119 | try { 120 | let x = onRejected(this.reason) 121 | resolvePromise(promise2, x, resolve, reject) 122 | 123 | } catch (error) { 124 | reject(error) 125 | } 126 | }, 0) 127 | }) 128 | 129 | } 130 | 131 | }) 132 | return promise2 133 | } 134 | 135 | catch(errCallback){ 136 | return this.then(null, errCallback) 137 | } 138 | } 139 | 140 | // 静态方法 141 | MyPromise.deferred = function () { 142 | let dfd = {} 143 | dfd.promise = new MyPromise((resolve, reject) => { 144 | dfd.resolve = resolve 145 | dfd.reject = reject 146 | }) 147 | return dfd 148 | } 149 | 150 | module.exports = MyPromise -------------------------------------------------------------------------------- /promise.js: -------------------------------------------------------------------------------- 1 | // promise then方法 then无限调用 2 | const PENDING = 'pending' // 等待 3 | const FULFILLED = 'fulfilled' // 成功 4 | const REJECTED = 'rejected' // 失败 5 | 6 | const resolvePromise = (promise2, x, resolve, reject) => { 7 | if (promise2 === x) { // 不能返回自己,死循环,直接抛出错误 8 | return reject(new TypeError('类型错误')) 9 | } 10 | // 判断x的状态 判断x是不是promise 11 | // 1.判断是不是对象或者函数 12 | if (typeof x === 'object' && x !== null || typeof x === 'function'){ 13 | // x需要是一个对象或者函数 14 | let called // 只能掉一个方法,失败或者成功,不能多吃调用成功或失败 15 | try { 16 | let then = x.then // 取出then方法 这个方法是采用defineProperty来定义的 17 | if (typeof then === 'function') { // 如果then不是一个函数,说明不是promise 18 | then.call(x, y => { // 将then作为this 19 | // resolve(y) // 如果是promise继续调用 20 | // console.log(99999) 21 | if (called) return 22 | called = true 23 | resolvePromise(promise2, y, resolve, reject) 24 | },r=>{ 25 | if (called) return 26 | called = true 27 | reject(r) 28 | }) 29 | } else { 30 | if (called) return 31 | called = true 32 | resolve(x) 33 | } 34 | } catch (error) { 35 | if (called) return 36 | called = true 37 | reject(error) 38 | } 39 | }else { 40 | resolve(x) 41 | } 42 | 43 | } 44 | class MyPromise { 45 | constructor(executor){ 46 | this.state = PENDING 47 | this.value = undefined 48 | this.reason = undefined 49 | this.onResolvedCallbacks = [] // 存放成功时的回调 50 | this.onRejectedCallbacks = [] // 存放失败时的回调 51 | let resolve = (value) =>{ 52 | if (value instanceof MyPromise) { 53 | return value.then(resolve, reject) 54 | } 55 | if (this.state === PENDING) { 56 | this.state = FULFILLED 57 | this.value = value 58 | this.onResolvedCallbacks.forEach(fn => fn()) 59 | } 60 | } 61 | let reject = (reason) => { 62 | if (this.state === PENDING) { 63 | this.state = REJECTED 64 | this.reason = reason 65 | this.onRejectedCallbacks.forEach(fn => fn()) 66 | } 67 | } 68 | try { // 只能捕获同步异常 69 | 70 | executor(resolve, reject) 71 | } catch (error) { 72 | reject(error) 73 | } 74 | } 75 | then(onfulfilled, onRejected){ 76 | // 可选参数处理 参数穿透 多次调用then 77 | onfulfilled = typeof onfulfilled === 'function'? 78 | onfulfilled: val => val 79 | onRejected = typeof onRejected === 'function'? 80 | onRejected: err => {throw err} 81 | // 递归 82 | let promise2 = new MyPromise((resolve, reject) => { 83 | if (this.state === FULFILLED) { 84 | setTimeout(() => { 85 | try { 86 | 87 | let x = onfulfilled(this.value) 88 | resolvePromise(promise2, x, resolve, reject) 89 | } catch (error) { 90 | reject(error) 91 | } 92 | }, 0) 93 | } 94 | if (this.state === REJECTED) { 95 | setTimeout(() => { 96 | try { 97 | let x = onRejected(this.reason) 98 | resolvePromise(promise2, x, resolve, reject) 99 | 100 | }catch(e){ 101 | reject(e) 102 | } 103 | }, 0) 104 | } 105 | if (this.state === PENDING) { 106 | // console.log(99) 107 | this.onResolvedCallbacks.push(()=>{ 108 | setTimeout(() => { 109 | try { 110 | let x = onfulfilled(this.value) 111 | resolvePromise(promise2, x, resolve, reject) 112 | } catch (error) { 113 | reject(error) 114 | } 115 | }, 0) 116 | }) 117 | this.onRejectedCallbacks.push(() => { 118 | setTimeout(() => { 119 | try { 120 | let x = onRejected(this.reason) 121 | resolvePromise(promise2, x, resolve, reject) 122 | 123 | } catch (error) { 124 | reject(error) 125 | } 126 | }, 0) 127 | }) 128 | 129 | } 130 | 131 | }) 132 | return promise2 133 | } 134 | 135 | catch(errCallback){ 136 | return this.then(null, errCallback) 137 | } 138 | } 139 | 140 | // 静态方法 141 | MyPromise.deferred = function () { 142 | let dfd = {} 143 | dfd.promise = new MyPromise((resolve, reject) => { 144 | dfd.resolve = resolve 145 | dfd.reject = reject 146 | }) 147 | return dfd 148 | } 149 | 150 | // 判断是不是promise 对象或者函数 有then方法 151 | function isPromise(value) { 152 | if ((typeof value === 'object' && value !== null) || typeof value === 'function'){ 153 | return typeof value.then === 'function' 154 | } 155 | return false 156 | } 157 | 158 | MyPromise.all = function (promises) { 159 | return new MyPromise((resolve, reject) => { 160 | let arr = [] // 返回的数组 161 | let processData = (i, data) => { 162 | arr[i] = data 163 | if (++i === promises.length) { 164 | resolve(arr) 165 | } 166 | } 167 | for (let i = 0; i < promises.length; i++) { 168 | const current = promises[i]; 169 | if (isPromise(current)) { 170 | current.then(data => { // 如果有一个失败直接失败 171 | processData(i, data) 172 | }, err =>{ 173 | reject(err) 174 | }) 175 | } else { 176 | processData(i, current) 177 | } 178 | } 179 | }) 180 | } 181 | 182 | module.exports = MyPromise --------------------------------------------------------------------------------