大致实现Promise

今天俺尝试一下实现Promise
1.下面代码实现不了micro task,所以resolve后,then中回调的函数是立即执行的。
2.then方法的作用是加入成功、失败回调函数的入口,以及获取成功value,失败reason的地方
//实现promise,有回调的地方需要保存this为ctx;不然this指向会有问题。下面实现中,只偶遇resolve和reject可能会出现回调的情况,then里面都是同步。
//另外,写代码时候想把status,回调函数等都保存在闭包中,来代替作为实例的属性,于是把prototype.then的内容放到了构造函数中。。。
//这会导致每次new时,prototype上的then都会被重写一次,结果会错误+。。。
function CustomPromise(execute) {
    
    
    this.status = 'pending';
    this.value = undefined;
    this.reason = '';
    this.resolveCallback = [];//其实最多一个函数
    this.rejectCallback =[];
    const ctx = this;
    try {
    
    
        execute(resolve, reject);
    } catch (e) {
    
    
        reject(e)
    }


    function resolve(value) {
    
    
        if (ctx.status === 'pending') {
    
    
            ctx.status = 'fulfilled'
            ctx.value = value;
            ctx.resolveCallback.forEach(fn => fn(value));
            ctx.resolveCallback.length = 0;// 此函数绝对不能被调用超过一次
        }
    }

    function reject(reason) {
    
    
        if (ctx.status === 'pending') {
    
    
            ctx.status = 'rejected';
            ctx.reason = reason;
            ctx.rejectCallback.forEach(fn => fn(reason))
            ctx.rejectCallback.length = 0;
        }
    }
}
CustomPromise.prototype.then = function (resolveFn, rejectFn) {
    
    //取value或者reason地方的地方
	//异步进入
    if (this.status === 'pending') {
    
    
        return new CustomPromise((resolve, reject) => {
    
    
            this.resolveCallback.push((value) => {
    
    //resolve方法中会传进来参数
                const result = resolveFn(value);
                if (result instanceof CustomPromise) {
    
    
                    result.then(resolve, reject);
                } else {
    
    
                    resolve(result);
                }
            });
            this.rejectCallback.push((reason) => {
    
    
                const result = resolveFn(reason);
                if (result instanceof CustomPromise) {
    
    
                    result.then(resolve, reject);
                } else {
    
    
                    reject(result);
                }
            })
        })
    }
//同步进入
    if (this.status === 'fulfilled') {
    
    
        return new CustomPromise((resolve, reject) => {
    
    
            const result = resolveFn(this.value); // 此函数必须在promise 完成(fulfilled)后被调用,并把promise 的值作为它的第一个参数
            if (result instanceof CustomPromise) {
    
    
                result.then(resolve, reject);
            } else {
    
    
                resolve(result);
            }
        })
    }

    if (this.status === 'rejected') {
    
    
        return new CustomPromise((resolve, reject) => {
    
    
            const result = rejectFn(this.reason);
            if (result instanceof CustomPromise) {
    
    
                result.then(resolve, reject);
            } else {
    
    
                reject(result);
            }
        })
    }
}
//Promise.prototype.catch()方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。
CustomPromise.prototype.catch = function(rejectFn){
    
    
	return this.then(null,rejectFn);
}
//静态方法CustomPromise.resolve写在后文
CustomPromise.prototype.finally = function(callback) {
    
    
	return this.then(
	value => CustomPromise.resolve(callback()).then(()=>value)),
	reason => CustomPromise.resolve(callback()).then(()=>throw reason))
)
}
//加入静态方法
//全部promise成功才返回
CustomPromise.all = function(...args){
    
    
	return new CustomPromise((resolve,reject)=>{
    
    
		const result = [];
		for(let item of ...args){
    
    
		//用到上述提到的第二点:then是获取成功失败的地方!!
			item.then(value=>{
    
    
				result.push(value);
				if(result.length === args.length)
					resolve(result);
			},reason=>{
    
    
				reject(reason)
			})
			//resolve和reject应该写在then的回调中,这里写的和参考的第一篇文字不太一样
		}
	});
}
任意一个promise成功/失败就返回
CustomPromise.race = function(...args){
    
    
	return new CustomPromise((resolve,reject)=>{
    
    
		for(let item of ...args){
    
    
			item.then(value=>{
    
    
				resolve(result);
			},reason=>{
    
    
				reject(reason)
			})
		}
	})
}
//直接返回一个成功的Promise
CustomPromise.resolve= function(data){
    
    
	return new CustomPromise((resolve,reject)=>{
    
    
		resolve(data);
	})
}
//直接返回一个失败的Promise
CustomPromise.reject= function(data){
    
    
	return new CustomPromise((resolve,reject)=>{
    
    
		reject(data);
	})
}

猜你喜欢

转载自blog.csdn.net/XIAOLONGJUANFENG/article/details/112760054
今日推荐