起因
前一段时间跟橡皮擦聊天,他说面试问到了 Promise 的实现方式。:) 菜鸡的我开始慌了。
一段 Promise 代码
new Promise((resolve, reject) => {
//code
}).then(data => {
}).then(data => {
})摆好姿势
还没有完全摆脱同步思维的我,卡在了 then 函数一块。在 Promise 状态发生变化之前,看起来代码就像停住了一样,在脑子里思考代码片段,并陷入了递归懵逼。还是去 google 吧。
基本介绍
A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its
thenmethod, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. — Promises/A+
Promise 代表了一个异步操作的最终结果。
let promise2 = new Promise(/*executor*/function(resolve, reject) {
//code
//resolve(value)
//reject(reason)
}).then(/*onFulfilled*/function(value){},
/*onRejected*/function(reason){})
promise只有三个状态pendingfulfillreject, 只能从pending转化为fulfill或者reject,一旦状态发生转换就不能再改变。new Promise的时候传入一个要执行的函数称为executorexecutor接收两个函数resolve和reject,调用这两个函数将使该promise状态发生改变。- 可以向
resolve和reject传入值,只是根据最终状态不同而有不同的称呼,分别为value 值和reason 拒绝的原因 promise可以使用then来注册两个函数onFulfiled和onRejected,当promise的状态从pending变化,将会根据结果调用注册的函数。then函数会返回一个新的promise,所以是promise2,而文章最开头的写法共有三个promise参与。
实现
实现的部分参考别人,里面有他的讲解(传送门),我只写下之前令我困惑的地方。
每次调用 then ,都会返回一个新的 Promise, 但是怎么进行链式的衔接呢? onFulfileed 和 onRejected 中没有可以直接调用的 resolve 或 reject 函数, 状态进行变化,向下传值。
Promise.prototype.then = function(onResolved, onRejected) {
// .....
/* promise2 */ return new Promise((resolve, reject) => {
let x = onResolved(data) // or onRejected(reason);
// 在 promise1 状态变化后,注册的回调函数将会 异步执行
// 而返回的 promise2 的状态将与回调函数的返回值有关 --promises/A+ 2.2.1.8节
resolvePromise(promise2, x, resolve, reject)
// 根据返回值 x 决定 promise2 的状态
// promises/A+ 2.3 The Promise Resolution Procedure
})
}
最后
自己对于一些常见的东西有些麻痹,应该保持一颗好奇心,将一些东西深究下去。