
Promise
写promise之前 ,我们先记下它的几个要点。
-
Promise是个类,类中的构造函数需要传入一个executor默认就会执行。 -
executor中有两个参数resolve,reject - 默认创建一个 Promise ,有三个状态:
pending、fulfilled、rejected - 调用成功 / 失败时,需要传递一个成功的原因,和失败的原因。
- 如果已经成功了 ,就不能再失败了。
- 如果抛出异常按失败处理
- 每个
promise实例上都有一个.then方法
首先新建一个 promise.js 文件 和 index.js 文件
// promise.js
const STATUS = {
PENDING: 'PENDING',
FULFILLED: 'FULFILLED',
REJECTED: 'REJECTED'
}
class Promise {
constructor(executor) {
this.status = STATUS.PENDING
this.value = undefined
this.reason = undefined
const resolve = val => {
if (this.status == STATUS.PENDING) {
this.status = STATUS.FULFILLED
this.value = val
}
}
const reject = reason => {
if (this.status == STATUS.PENDING) {
this.status = STATUS.REJECTED
this.reason = reason
}
}
try {
executor(resolve, reject)
} catch (e) {
// 失败走失败的逻辑处理
reject(e)
}
}
then(onfulfilled, onRejected) {
if (this.status == STATUS.FULFILLED) {
onfulfilled(this.value)
}
if (this.status == STATUS.REJECTED) {
onRejected(this.reason)
}
}
}
module.exports = Promise
// index.js
const Promise = require('./promise.js')
let p = new Promise((resolve, reject) => {
// throw new Error('aa')
// reject('失败了')
resolve('成功了')
})
p.then(
data => {
console.log('success', data)
},
reason => {
console.log('fail', reason)
}
)
目前这个最基本的简洁版的Promise就实现了。后面还有很多 ,目前的Promise 还是同步的 , 我们会继续完成。
[下一篇 3. 手写Promise]
更多知识点 请关注:笔墨是小舟