自定义手写Promise

简介: 手写函数版和类版Promise

函数版:
function diyPromise(executor) {

//添加属性
this.PromiseState = 'pending';
this.PromiseResult = null;
this.callbacks = [];
//保存实例对象 this的值为diyPromise
const self = this;
//reslove函数
function resolve(data) {
    //设置promise对象状态只能由pending到其他状态且只修改一次
    if (self.PromiseState !== 'pending') return;
    //修改对象的状态
    self.PromiseState = 'resolved';
    //修改对象结果值
    self.PromiseResult = data
        //调用成功的回调函数
    setTimeout(() => {
        self.callbacks.forEach(item => {
            item.onResolved(data)
        })
    })

}
//reject函数
function reject(data) {
    //设置promise对象状态只能由pending到其他状态且只修改一次
    if (self.PromiseState !== 'pending') return;
    //修改对象的状态
    self.PromiseState = 'rejected';
    //修改对象结果值
    self.PromiseResult = data
        //调用失败的回调函数
    setTimeout(() => {
        self.callbacks.forEach(item => {
            item.onRejected(data)
        })
    })

}

//同步调用 [执行器函数]
try {
    executor(resolve, reject);
} catch (error) {
    reject(error);
}

}

//添加then方法回调
diyPromise.prototype.then = function(onResolved, onRejected) {
//判断回调函数参数
if (typeof onRejected !== 'function') {
onRejected = reason => {
throw reason;
}
}
if (typeof onResolved !== 'function') {
onResolved = value => value;
// value = {return value}
}
//保存实例对象的值
const self = this;
return new diyPromise((resolve, reject) => {
//封装函数
function callback(type) {
try {
//获取回调函数的执行结果
let result = type(self.PromiseResult);
//判断 获取的执行结果是否是Promise实例
if (result instanceof diyPromise) {
//如果是Promise类型的对象
result.then(v => {
resolve(v)
}, r => {
reject(r);
})
} else {
//如果是非Promise对象 更改Promise状态为成功
resolve(result);
}
} catch (error) {
reject(error)
}
}
//调用回调函数
if (this.PromiseState === 'resolved') {
setTimeout(() => {
callback(onResolved)
})
}

        if (this.PromiseState === 'rejected') {
            setTimeout(() => {
                callback(onRejected);
            })
        }
        //判断 pending状态
        if (this.PromiseState === 'pending') {
            //保存回调函数
            this.callbacks.push({
                onRejected: function() {
                    callback(onResolved)
                },

                onResolved: function() {
                    callback(onRejected)
                }
            })
        }
    })
}
//添加catch方法

diyPromise.prototype.catch = function(onRejected) {
return this.then(undefined, onRejected);
}

//添加resolve方法
diyPromise.resolve = function(value) {
//返回Promise对象
return new diyPromise((resolve, reject) => {
if (value instanceof diyPromise) {
value.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
//状态设置为成功
resolve(value);
}
})
}
//添加reject方法
diyPromise.reject = function(reason) {
return new diyPromise((resolve, reject) => {
reject(reason);
})
}
//添加all方法
diyPromise.all = function(promises) {
//返回结果为promise对象
return new diyPromise((resolve, reject) => {
//声明变量
let count = 0;
let arr = [];
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
//得知对象的状态是成功
//每个promise对象都成功
count++;
//将当前promise对象成功的结果存入到 集合中
arr[i] = v;
//判断 是否所有的promise都成功了
if (count === promises.length) {
//修改状态
resolve(arr);
}
}, r => {
reject(r);
});
}
})
}
//添加rece方法
diyPromise.race = function(promises) {
return new diyPromise((resolve, reject) => {
// // for (let i = 0; i < promises.length; i++) {
// promises[i].then(v => {
// //修改返回对象状态为 [成功]
// resolve(v);
// }, r => {
// //修改返回对象状态为 [失败]
// reject(r);
// })

    // }
    for (let key of promises) {
        key.then(v => {
            //修改返回对象状态为 [成功]
            resolve(v);
        }, r => {
            //修改返回对象状态为 [失败]
            reject(r);
        })
    }
})

}

类版:
class diyPromise {
constructor(executor) {
//添加属性
this.PromiseState = 'pending';
this.PromiseResult = null;
this.callbacks = [];
//保存实例对象 this的值为diyPromise
const self = this;
//reslove函数
function resolve(data) {
//设置promise对象状态只能由pending到其他状态且只修改一次
if (self.PromiseState !== 'pending') return;
//修改对象的状态
self.PromiseState = 'resolved';
//修改对象结果值
self.PromiseResult = data
//调用成功的回调函数
setTimeout(() => {
self.callbacks.forEach(item => {
item.onResolved(data)
})
})

    }
    //reject函数
    function reject(data) {
        //设置promise对象状态只能由pending到其他状态且只修改一次
        if (self.PromiseState !== 'pending') return;
        //修改对象的状态
        self.PromiseState = 'rejected';
        //修改对象结果值
        self.PromiseResult = data
            //调用失败的回调函数
        setTimeout(() => {
            self.callbacks.forEach(item => {
                item.onRejected(data)
            })
        })

    }

    //同步调用 [执行器函数]
    try {
        executor(resolve, reject);
    } catch (error) {
        reject(error);
    }
}
then(onResolved, onRejected) {
    //判断回调函数参数
    if (typeof onRejected !== 'function') {
        onRejected = reason => {
            throw reason;
        }
    }
    if (typeof onResolved !== 'function') {
        onResolved = value => value;
        // value = {return value}
    }
    //保存实例对象的值
    const self = this;
    return new diyPromise((resolve, reject) => {
        //封装函数
        function callback(type) {
            try {
                //获取回调函数的执行结果
                let result = type(self.PromiseResult);
                //判断 获取的执行结果是否是Promise实例
                if (result instanceof diyPromise) {
                    //如果是Promise类型的对象
                    result.then(v => {
                        resolve(v)
                    }, r => {
                        reject(r);
                    })
                } else {
                    //如果是非Promise对象 更改Promise状态为成功
                    resolve(result);
                }
            } catch (error) {
                reject(error)
            }
        }
        //调用回调函数
        if (this.PromiseState === 'resolved') {
            setTimeout(() => {
                callback(onResolved)
            })
        }

        if (this.PromiseState === 'rejected') {
            setTimeout(() => {
                callback(onRejected);
            })
        }
        //判断 pending状态
        if (this.PromiseState === 'pending') {
            //保存回调函数
            this.callbacks.push({
                onRejected: function() {
                    callback(onResolved)
                },

                onResolved: function() {
                    callback(onRejected)
                }
            })
        }
    })
}
catch (onRejected) {
    return this.then(undefined, onRejected);
}
static resolve(value) {
        //返回Promise对象
        return new diyPromise((resolve, reject) => {
            if (value instanceof diyPromise) {
                value.then(v => {
                    resolve(v);
                }, r => {
                    reject(r);
                })
            } else {
                //状态设置为成功
                resolve(value);
            }
        })
    }
    //添加reject方法
static reject(reason) {
        return new diyPromise((resolve, reject) => {
            reject(reason);
        })
    }
    //添加all方法
static all(promises) {
        //返回结果为promise对象
        return new diyPromise((resolve, reject) => {
            //声明变量
            let count = 0;
            let arr = [];
            for (let i = 0; i < promises.length; i++) {
                promises[i].then(v => {
                    //得知对象的状态是成功 
                    //每个promise对象都成功
                    count++;
                    //将当前promise对象成功的结果存入到 集合中
                    arr[i] = v;
                    //判断 是否所有的promise都成功了
                    if (count === promises.length) {
                        //修改状态
                        resolve(arr);
                    }
                }, r => {
                    reject(r);
                });
            }
        })
    }
    //添加rece方法
static race(promises) {
    return new diyPromise((resolve, reject) => {
        // // for (let i = 0; i < promises.length; i++) {
        //     promises[i].then(v => {
        //         //修改返回对象状态为 [成功]
        //         resolve(v);
        //     }, r => {
        //         //修改返回对象状态为 [失败]
        //         reject(r);
        //     })

        // }
        for (let key of promises) {
            key.then(v => {
                //修改返回对象状态为 [成功]
                resolve(v);
            }, r => {
                //修改返回对象状态为 [失败]
                reject(r);
            })
        }
    })
}

}

相关文章
|
6月前
|
前端开发 JavaScript
在JavaScript中,什么是promise、怎么使用promise、怎么手写promise
在JavaScript中,什么是promise、怎么使用promise、怎么手写promise
99 4
|
前端开发
手写基础 promise
手写基础 promise
66 0
|
存储 前端开发
|
前端开发
Promise的用法&原理&手写实现-2
Promise的用法&原理&手写实现-2
42 1
|
6月前
|
前端开发 JavaScript API
手写promise
手写promise
40 0
|
前端开发 JavaScript API
Promise的用法&原理&手写实现-1
Promise的用法&原理&手写实现-1
54 0
|
前端开发
手写Promise
手写Promise
|
存储 前端开发 JavaScript
PromiseA+规范之手写Promise
PromiseA+规范之手写Promise
PromiseA+规范之手写Promise
|
前端开发
手写Promise核心代码
手写Promise核心代码
179 0
|
前端开发 JavaScript 开发者
Promise从手写到扩展 | Promise/Generator/async | [Promise系列二](一)
Promise从手写到扩展 | Promise/Generator/async | [Promise系列二](一)
113 0