基于promise A+规范文档实现,保证promise之间有相互的兼容性
promiseA+ 规范文档,https://promisesaplus.com/
兼容:
es6内部已经实现,ie全部不支持promise,需要polyfill来做兼容
promise为什么会产生?
- 多个异步请求并发 Promise.all()
- 链式异步请求,上个人的输出是下个人的输入,解决回调地狱
- 缺点,还是基于回调函数
简单的promise
- promise 有三个状态,成功态,失败态,等待态
- 成功失败是自定义的
- promise默认执行器是立即执行
- promise的实例都拥有一个then方法,有两个参数,一个是成功的回调,一个是失败的回调
- 如果执行函数时,发生异常也会执行失败逻辑
- 如果成功就不能失败,反之,如果失败,就不能成功,只有等待态,才能改变状态
promise.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| const FULFILLED = 'fulfilled'; const REJECTED = 'rejected'; const PENDING = 'pending';
class Promise { constructor(executer) { this.status = PENDING; this.value = undefined; this.reason = undefined; console.log('my promise') const resolve = (value) => { if (this.status === PENDING) { this.value = value; this.status = FULFILLED; } } const reject = (reason) => { if (this.status === PENDING) { this.reason = reason; this.status = REJECTED; } }
try { executer(resolve, reject); } catch (error) { reject(error) } }
then(onFulfilled, onRejected) { if (this.status === FULFILLED) { onFulfilled(this.value); }
if (this.status === REJECTED) { onRejected(this.reason); } } }
module.exports = Promise;
|
index.js
1 2 3 4 5 6 7 8 9 10 11
| const Promise = require('./promise.js');
let task = new Promise((resolve, reject) => { resolve(1) reject('报错了') }) task.then(res => { console.log(res) }, err => {
})
|