写前端也有几年了,最近在整理知识点,看了一遍promiseA+的规范,就想自己写一遍这个前端异步流程控制的经典函数。
先用个简单的例子演示一下promise是怎么工作的。
let myFirstPromise = new Promise(function(resolve, reject){
//当异步代码setTimeout执行成功时,我们才会调用resolve(...), 当异步代码失败时就会调用reject(...)
//如果执成功回调resolve,则永远不会再走到reject
//promise成功和失败状态是我们自己手动控制的
//在本例中,我们使用setTimeout(...)来模拟异步代码,实际编码时可能是XHR请求或是HTML5的一些API方法.
setTimeout(function(){
resolve("成功!"); //代码正常执行!
}, 250);
});
myFirstPromise.then(function(successMessage){
//successMessage的值是上面调用resolve(...)方法传入的值.
//successMessage参数不一定非要是字符串类型,这里只是举个例子
console.log("Yay! " + successMessage);
});
下面按promiseA+的规范自己实现一个promise
先写一个构造函数 供外部调用
executor是带有 resolve 和 reject 两个参数的函数 。Promise构造函数执行时立即调用executor 函数, resolve 和 reject 两个函数作为参数传递给executor。resolve 和 reject 函数被调用时,分别将promise的状态改为fulfilled(完成)或rejected(失败)。executor 内部通常会执行一些异步操作,一旦完成,可以调用resolve函数来将promise状态改成fulfilled,或者在发生错误时将它的状态改为rejected。
如果在executor函数中抛出一个错误,那么该promise 状态为rejected。executor函数的返回值被忽略。
var promise = new Promise(function(resolve, reject) {
// 成功的话调用resolve并传入value
// 失败的话调用reject并传入reason
})
第二步 写构造函数的框架
function Promise(executor) {
let self = this
//由于promise异步回调方法,所以必须有等待状态,成功状态,失败状态。
self.status = 'pending' // Promise当前的状态
self.data = undefined // Promise的值
self.onResolvedCallback = [] // Promise resolve时的回调函数集,因为在Promise结束之前有可能有多个回调添加到它上面
self.onRejectedCallback = [] // Promise reject时的回调函数集,因为在Promise结束之前有可能有多个回调添加到它上面
executor(resolve, reject) // 执行executor并传入相应的参数
}
第三步,实现resolve和reject和内部抛出异常时立即将promise改为reject状态
function Promise(executor) {
let self = this
self.status = 'pending' // Promise当前的状态
self.data = undefined // Promise的值
self.onResolvedCallback = [] // Promise resolve时的回调函数集,因为在Promise结束之前有可能有多个回调添加到它上面
self.onRejectedCallback = [] // Promise reject时的回调函数集,因为在Promise结束之前有可能有多个回调添加到它上面
function resolve(value) {
//resolve方法,后边会用到
if (self.status === 'pending') {
self.status = 'resolved'
self.data = value
//有可能调用多次resolve,把多个回调存到成功数组里
for(var i = 0; i < self.onResolvedCallback.length; i++) {
self.onResolvedCallback[i](value)
}
}
}
function reject(reason) {
// reject方法,后边会用到
if (self.status === 'pending') {
self.status = 'rejected'
self.data = reason
//原因同上
for(var i = 0; i < self.onRejectedCallback.length; i++) {
self.onRejectedCallback[i](reason)
}
}
}
try { // 执行executor的过程出错,所以我们用try/catch块给包起来,并且在出错后以catch到的值reject掉这个Promise
executor(resolve, reject) // 执行executor
} catch(e) {
//出错之后调用reject
reject(e)
}
}
promise的then方法(解决洋葱式的语法结构)
原生Promise对象有一个then方法,用来实现在这个Promise状态确定后的回调那么这个then方法需要写在原型链上。then方法会返回一个新的Promise,这样就实现了链式调用,从而避免了之前callback回调的那种洋葱结构,使程序更简单易懂。
Promise.prototype.then = function(onResolved, onRejected) {
let self = this
let promise2
// 根据promiseA+,如果then的参数不是function,则我们需要忽略它,此处以如下方式处理
onResolved = typeof onResolved === 'function' ? onResolved : function(v) {}
onRejected = typeof onRejected === 'function' ? onRejected : function(r) {}
if (self.status === 'resolved') {
return promise2 = new Promise(function(resolve, reject) {
})
}
if (self.status === 'rejected') {
return promise2 = new Promise(function(resolve, reject) {
})
}
if (self.status === 'pending') {
return promise2 = new Promise(function(resolve, reject) {
})
}
}
因为then方法返回一个新的promise,所以我们需要在then里面执行onResolved或者onRejected,并根据返回值来确定新的promise的结果,而且,如果onResolved/onRejected返回的是一个Promise,promise2将直接取这个Promise的结果:直接看代码
Promise.prototype.then = function(onResolved, onRejected) {
var self = this
var promise2
onResolved = typeof onResolved === 'function' ? onResolved : function(value) {}
onRejected = typeof onRejected === 'function' ? onRejected : function(reason) {}
if (self.status === 'resolved') {
// 如果promise状态已经确定并且是resolved,我们调用onResolved
// 因为考虑到有可能抛出异常,所以我们将其包在try/catch块里
return promise2 = new Promise(function(resolve, reject) {
try {
var x = onResolved(self.data)
if (x instanceof Promise) { // 如果onResolved的返回值是一个Promise对象,直接取它的结果做为promise2的结果,做到链式调用
x.then(resolve, reject)
}
resolve(x) // 否则,以它的返回值做为promise2的结果
} catch (e) {
reject(e) // 如果出错,以捕获到的错误做为promise2的结果
}
})
}
// 此处逻辑与resolve相同
if (self.status === 'rejected') {
return promise2 = new Promise(function(resolve, reject) {
try {
var x = onRejected(self.data)
if (x instanceof Promise) {
x.then(resolve, reject)
}
} catch (e) {
reject(e)
}
})
}
if (self.status === 'pending') {
// 由于Promise还有pending状态,我们并不能确定调用onResolved还是onRejected,需要确定promise的状态才能进行下一步的处理
// 逻辑与resolve一致
return promise2 = new Promise(function(resolve, reject) {
self.onResolvedCallback.push(function(value) {
try {
var x = onResolved(self.data)
if (x instanceof Promise) {
x.then(resolve, reject)
}
} catch (e) {
reject(e)
}
})
self.onRejectedCallback.push(function(reason) {
try {
var x = onRejected(self.data)
if (x instanceof Promise) {
x.then(resolve, reject)
}
} catch (e) {
reject(e)
}
})
})
}
}
这样我我们就实现了一个简单的promise,与官方promise基本一致,不过还有个问题,如果调用多个then,不过并没有返回值,例如这样
new Promise(resolve=>resolve(“呵呵呵”))
.then()
.then()
.then(function foo(value) {
alert(value)
})
只在最后一个then出现返回值,那么就需要把promise的返回值直接传到最后一个then中,这里,我们做一个值的穿透,如果没有返回值,那么就把resolve向下抛。
onResolved = typeof onResolved === 'function' ? onResolved : function(value) {return value}
onRejected = typeof onRejected === 'function' ? onRejected : function(reason) {throw reason}
最后一点,在看promiseA+规范的时候发现then的回调需要异步执行,这里没有仔细思考过原因,在网上找过一些资料后觉得,promise异步执行的原因主要是防止栈溢出和保持执行的一致性,promiseA+的标准给出的是要返回new Promise到jobQuene js的运行时里对jobQuene和eventLoop的处理还是有一些差异的。不同之处在于
每个 JavaScript Runtime 可以有多个 Job Queue,但只有一个 Event Loop Queue当 JavaScript Engine 处理完当前事件队列中的代码后,再执行本次任务中所有的 Job Queue,然后再处理 Event Loop Queue(下一次事件循环任务)
所以这里为了模拟jobQuene 我们把promise执行回调放在setTimeout中,保证回调异步执行,上代码
function Promise(executor) {
var self = this
self.status = 'pending'
self.onResolvedCallback = []
self.onRejectedCallback = []
function resolve(value) {
if (value instanceof Promise) {
return value.then(resolve, reject)
}
// 异步回调函数
setTimeout(function() {
if (self.status === 'pending') {
self.status = 'resolved'
self.data = value
for (var i = 0; i < self.onResolvedCallback.length; i++) {
self.onResolvedCallback[i](value)
}
}
})
}
function reject(reason) {
// 异步回调函数
setTimeout(function() {
if (self.status === 'pending') {
self.status = 'rejected'
self.data = reason
for (var i = 0; i < self.onRejectedCallback.length; i++) {
self.onRejectedCallback[i](reason)
}
}
})
}
try {
executor(resolve, reject)
} catch (reason) {
reject(reason)
}
}
function resolvePromise(promise2, x, resolve, reject) {
var then
var thenCalledOrThrow = false
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise!'))
}
if (x instanceof Promise) {
if (x.status === 'pending') { //because x could resolved by a Promise Object
x.then(function(v) {
resolvePromise(promise2, v, resolve, reject)
}, reject)
} else { //but if it is resolved, it will never resolved by a Promise Object but a static value;
x.then(resolve, reject)
}
return
}
if ((x !== null) && ((typeof x === 'object') || (typeof x === 'function'))) {
try {
then = x.then //because x.then could be a getter
if (typeof then === 'function') {
then.call(x, function rs(y) {
if (thenCalledOrThrow) return
thenCalledOrThrow = true
return resolvePromise(promise2, y, resolve, reject)
}, function rj(r) {
if (thenCalledOrThrow) return
thenCalledOrThrow = true
return reject(r)
})
} else {
resolve(x)
}
} catch (e) {
if (thenCalledOrThrow) return
thenCalledOrThrow = true
return reject(e)
}
} else {
resolve(x)
}
}
Promise.prototype.then = function(onResolved, onRejected) {
var self = this
var promise2
onResolved = typeof onResolved === 'function' ? onResolved : function(v) {
return v
}
onRejected = typeof onRejected === 'function' ? onRejected : function(r) {
throw r
}
if (self.status === 'resolved') {
return promise2 = new Promise(function(resolve, reject) {
setTimeout(function() { // 异步执行onResolved
try {
var x = onResolved(self.data)
resolvePromise(promise2, x, resolve, reject)
} catch (reason) {
reject(reason)
}
})
})
}
if (self.status === 'rejected') {
return promise2 = new Promise(function(resolve, reject) {
// 异步执行onRejected
setTimeout(function() {
try {
var x = onRejected(self.data)
resolvePromise(promise2, x, resolve, reject)
} catch (reason) {
reject(reason)
}
})
})
}
if (self.status === 'pending') {
return promise2 = new Promise(function(resolve, reject) {
self.onResolvedCallback.push(function(value) {
try {
var x = onResolved(value)
resolvePromise(promise2, x, resolve, reject)
} catch (r) {
reject(r)
}
})
self.onRejectedCallback.push(function(reason) {
try {
var x = onRejected(reason)
resolvePromise(promise2, x, resolve, reject)
} catch (r) {
reject(r)
}
})
})
}
}
至此,一个promise的实现就已经写完了,后面附上promise all和promise race的方法实现
all
var p1 = Promise.resolve(1),
p2 = Promise.resolve(2),
p3 = Promise.resolve(3);
Promise.all([p1, p2, p3]).then(function (results) {
console.log(results);
});
// 结果[1, 2, 3]
只有所有promise全都返回的时候,才执行resolve方法
Promise.all = function(arr){
return new Promise((resolve,reject)=>{
let list=[];
arr.forEach((item)=>{
item.then((data)=>{
list.push(data);
if(arr.length == list.length){
resolve(resolvList);
}
},(reason)=>{
reject(reason);
})
})
})
}
race
只要有一个成功就立即返回。
var p1 = Promise.resolve(1),
p2 = Promise.resolve(2),
p3 = Promise.resolve(3);
Promise.race([p1, p2, p3]).then(function (value) {
console.log(value); // 1
});
//结果 1
Promise.all = function(arr){
return new Promise((resolve,reject)=>{
let list=[];
arr.forEach((item)=>{
item.then((data)=>{
resolve(resolvList);
},(reason)=>{
reject(reason);
})
})
})
}