promise
是异步编程的一种解决方法,比传统的回调函数和事件更合理更强大。
他由社区最早提出和实现,ES6将其写进语言标准,统一了用法,原生提供了Promise
对象。
所谓promise
,简单说是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果
从语法上说,promise
是一个对象,从它可以获取异步操作的消息,
promise
提供了统一的API,各种异步操作都可以用同样的方法进行处理。
Promise 表示一个异步操作的最终结果,与之进行交互的方式主要是 then 方法,该方法注册了两个回调函数,用于接收 promise 的终值或本 promise 不能执行的原因。
Promise
的实现遵循 Promises/A+
规范,详细内容:
英文版:https://promisesaplus.com/
中文版1:https://www.ituring.com.cn/article/66566
中文版2:https://segmentfault.com/a/1190000002452115
原生Promise
使用方法:
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
promise1.then((value) => {
console.log(value); // expected output: "foo"
});
手写实现:
// 状态定义
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
// Promise 解决过程
const resolvePromise = (promise, x, resolve, reject) => {
// 如果 promise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 promise
if (promise === x) {
return reject(new TypeError('Chaining cycle detected for promise #'))
}
let called;
// 后续的条件要严格判断 保证代码能和别的库一起使用
if ((typeof x === 'object' && x != null) || typeof x === 'function') {
try {
// 为了判断 resolve 过的就不用再 reject 了(比如 reject 和 resolve 同时调用的时候) Promise/A+ 2.3.3.1
let then = x.then;
if (typeof then === 'function') {
// 不要写成 x.then,直接 then.call 就可以了 因为 x.then 会再次取值,Object.defineProperty Promise/A+ 2.3.3.3
then.call(x, y => { // 根据 promise 的状态决定是成功还是失败
if (called) return;
called = true;
// 递归解析的过程(因为可能 promise 中还有 promise) Promise/A+ 2.3.3.3.1
resolvePromise(promise, y, resolve, reject);
}, r => {
// 只要失败就失败 Promise/A+ 2.3.3.3.2
if (called) return;
called = true;
reject(r);
});
} else {
// 如果 x.then 是个普通值就直接返回 resolve 作为结果 Promise/A+ 2.3.3.4
resolve(x);
}
} catch (e) {
// Promise/A+ 2.3.3.2
if (called) return;
called = true;
reject(e)
}
} else {
// 如果 x 是个普通值就直接返回 resolve 作为结果 Promise/A+ 2.3.4
resolve(x)
}
}
class MyPromise {
constructor(executor) {
this.state = PENDING;
this.onResloveList = []
this.onRejectList = []
this.value = undefined;
this.reason = undefined;
let resolve = (value) => {
if (this.state == PENDING) {
this.state = FULFILLED;
this.value = value;
this.onResloveList.forEach(fn => fn())
}
}
let reject = (reason) => {
if (this.state == PENDING) {
this.state = REJECTED;
this.reason = reason;
this.onRejectList.forEach(fn => fn())
}
}
try {
executor(resolve, reject)
} catch (error) {
console.log('catch...' + error)
reject(error)
}
}
then(onFulfilled, onRejected) {
// 值穿透
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err }
let thenPromise = new MyPromise((resolve, reject) => {
switch (this.state) {
case PENDING: // 执行状态
this.onResloveList.push((value) => {
try {
let x = onFulfilled(this.value)
resolvePromise(thenPromise, x, resolve, reject)
} catch (e) {
reject(e)
}
})
this.onRejectList.push((value) => {
try {
let x = onRejected(this.reason)
resolvePromise(thenPromise, x, resolve, reject)
} catch (e) {
reject(e)
}
})
break;
case FULFILLED: // 完成状态
setTimeout(() => {
try {
let x = onFulfilled(this.value)
resolvePromise(thenPromise, x, resolve, reject)
} catch (e) {
reject(e)
}
}, 0);
break;
case REJECTED: // 失败状态
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e)
}
}, 0);
break;
default:
break;
}
})
return thenPromise
}
catch = (rejected) => {
this.then(null, rejected)
}
}
MyPromise.all = function(values) {
if (!Array.isArray(values)) {
const type = typeof values;
return new TypeError(`TypeError: ${type} ${values} is not iterable`)
}
return new Promise((resolve, reject) => {
let resultArr = [];
let orderIndex = 0;
const processResultByKey = (value, index) => {
resultArr[index] = value;
if (++orderIndex === values.length) {
resolve(resultArr)
}
}
for (let i = 0; i < values.length; i++) {
let value = values[i];
if (value && typeof value.then === 'function') {
value.then((value) => {
processResultByKey(value, i);
}, reject);
} else {
processResultByKey(value, i);
}
}
});
}
验证:
new MyPromise((resolve, reject) => {
console.log(0, 'create')
setTimeout(() => {
console.log(1, 'timeout')
resolve('123')
}, 500);
})
.then(res => {
console.log(2, res)
return res
})
.then(res => {
console.log(3, res)
return res
})
.then()
.then(res => {
console.log(4, res)
return new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('456')
}, 500);
})
})
.then(res => {
console.log(5, res)
return res
})
.then(res => {
console.log(6, res)
console.log(a)
})
.catch(err => {
console.log(7, err)
})
// 输出:
// 0 "create"
// 1 "timeout"
// 2 "123"
// 3 "123"
// 4 "123"
// 5 "456"
// 6 "456"
// 7 ReferenceError: a is not defined
原生Promise
的实现是微任务,本文用setTimeout
替代实现