欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

前端企业面试题:企业真实案例——33

程序员文章站 2022-06-04 14:43:52
...
手动实现一个Promise
function MyPromise(main){
    let status = "pending"; //Promise对象状态
    let tasklist = []; //保存所有的任务
    let exceptionHander = null;			

    function resolve(msg) {
        if(status == "pending") {
	    status = "resovled"; //修改状态为resolved
	    let next = tasklist.shift(); //从任务队列取出第一个
	    let newp = next(msg); //执行
	    if( newp instanceof MyPromise ) { //若有新的Promise出现
                //将当前任务队列当中,剩余的任务,交接给下一个Promise
                tasklist.forEach( t=>{ 
                    newp.then( t )
                })
            } 
        }
    }
			
    function reject(msg) {
        if( status == "pending") { //防止状态二次修改
            status = "rejected";
	    exceptionHander ? exceptionHander(msg): throw new Error(msg); //执行异常处理
        }
    }

    this.then = function( task ){
        tasklist.push(task); //将任务存入队列当中
        return this;
    }
    this.catch = function( fn ){
        exceptionHander = fn;
    }
    this.getStatus = function(){
        return status;
    }
			
    setTimeout(()=>{
        main(resolve, reject);
    }, 0)
}

Promise.all 实现

MyPromise.all = function(args){
	let count = 0;
	let task = null;
	function resolve() {
		count++;
		if(count == args.length) task();
	}
	args.forEach(p=>{
		p.then(resolve);
	})
	
	return {
		then( fn ){
			task = fn;
		}
	}
}