首页 > 其他分享 >手写Promise

手写Promise

时间:2024-05-26 15:37:34浏览次数:9  
标签:status MyPromise promise result Promise 手写 onREJECTED

目录

promise的原理

  • 回调地狱:当想要异步任务按顺序执行时,用回调函数套回调函数实现,这种情况就叫回调地狱。
  • promise就是用来解决回调地狱问题的
  • promise在A+规范里面就是一个带.then()方法的对象或函数
  • promise在ES6里面,是一个构造函数,通过这个构造函数创建的实例满足了promiseA+规范
  • promise有三种状态:Pending(进行中)、Fulfilled(已成功)、Rejected(已失败)。一个 Promise 对象只能从 Pending 状态转换到 Fulfilled 或 Rejected 状态,并且状态转换是不可逆的。
  • 在函数内返回一个promise对象,可以接着.then(),不需要套娃操作。
  • .then一大堆,可以用建立在 Promise 之上的语法糖async/await,把本来是异步的代码,看上去是同步。

手写Promise

class MyPromise{
    //有三种状态
    static PENDING='待定'; FULFILLED='成功';REJECTED='拒绝';
    constructor(func){
        //设置默认状态为pending
        this.status=MyPromise.PENDING;
        this.result=null;
        this.resolveCallbacks=[];
        this.rejectCallbacks=[];
        try{
            func(this.resolve.bind(this),this.reject.bind(this));//加上bind解决this指向问题
        }catch(error){
            this.reject(error);
        }
        
    }
    resolve(result){
        setTimeout(()=>{
            if(this.status===MyPromise.PENDING){
                this.status=MyPromise.FULFILLED;
                this.result=result;
                this.resolveCallbacks.forEach(callback=>{
                    callback(result)
                });
            }
        })
    }
    reject(result){
        setTimeout(()=>{
            if(this.status===MyPromise.PENDING){
                this.status=MyPromise.REJECTED;
                this.result=result;
                this.rejectCallbacks.forEach(callback=>{
                    callback(result)
                });
            }
        })
    }
    //只会执行成功或者失败
    then(onFULFILLED,onREJECTED){
        //返回promise对象,保证then的链式
        return new MyPromise(()=>{
            //确保传入参数
        onFULFILLED=typeof onFULFILLED === 'function'?onFULFILLED:()=>{};
        onREJECTED=typeof onREJECTED === 'function'?onREJECTED:()=>{};
        if (this.status===MyPromise.PENDING){
            this.resolveCallbacks.push(onFULFILLED);
            this.resolveCallbacks.push(onREJECTED);   
        }
        if (this.status===MyPromise.FULFILLED){
            setTimeout(()=>{
                onFULFILLED(this.result);
            });
        }
        if (this.status===MyPromise.REJECTED){
            setTimeout(()=>{
                onREJECTED(this.result);
            })
        }
        })
    }
}

标签:status,MyPromise,promise,result,Promise,手写,onREJECTED
From: https://www.cnblogs.com/lushuang55/p/18213729

相关文章

  • 从零手写实现 nginx-01-为什么不能有 java 版本的 nginx?
    前言大家好,我是老马。很高兴遇到你。作为一个java开发者,工作中一直在使用nginx。却发现一直停留在使用层面,无法深入理解。有一天我在想,为什么不能有一个java版本的nginx呢?一者是理解nginx的设计灵魂,再者java开发者用java语言的服务器不是更加自然吗。于是动手开......
  • Pytorch-08 实战:手写数字识别
    手写数字识别项目在机器学习中经常被用作入门练习,因为它相对简单,但又涵盖了许多基本的概念。这个项目可以视为机器学习中的“HelloWorld”,因为它涉及到数据收集、特征提取、模型选择、训练和评估等机器学习中的基本步骤,所以手写数字识别项目是一个很好的起点。我们的要做......
  • 手写promise
    constpending='pending'constfulfilled='fulfilled'constrejected='rejected'classMyPromise{#state=pending#result=undefined#handler=[]constructor(exector){constresolve=(data)=>{......
  • 关于async/await、promise和setTimeout执行顺序
    前段时间领导给我们出了一道题,关于async/await、promise和setTimeout的执行顺序,网上查了查资料,这是头条的一道笔试题,记录一下,加深理解。题目如下:asyncfunctionasync1(){console.log('async1start');awaitasync2();console.log('asnyc1end');}asyncfunc......
  • [ES2024] Manually settle a promise using Promise.withResolvers
    Ifwewanttobeabletomodifythestateofapromisefromoutsidetheconstructor,wecanusethe Promise.withResolvers methodtogetaccesstothepromise,andits resolve and reject functions. //oldapproachletres,rej;constpromise=newPr......
  • Promise 的完全实现
    零、参考资料手把手一行一行代码教你“手写Promise“,完美通过Promises/A+官方872个测试用例手写实现Promise全部实例方法和静态方法,来看看Promise.all、Promise.race和Promise.any都是怎么实现的JS/ES6Promise的不完全实现 一、具体代码exportdefaultcl......
  • JavaScript execute asynchronous functions in Parallel with count and Promise All
    JavaScriptexecuteasynchronousfunctionsinParallelwithcountandPromiseAllInOneJavaScript使用count和Promise并行执行异步函数errorsfunctionpromiseAll<T>(functions:Fn<T>[]):Promise<T[]>{returnnewPromise((resolve,reject)=&......
  • promise(A).catch(f1).then(f2),f1执行后f2回执行吗,为什么
    在JavaScript中,Promise链中的.catch()方法用于捕获前面Promise中的错误,并且无论这个错误是在.then()链中的哪一个环节产生的,.catch()都会捕获到。当错误被.catch()处理之后,如果希望后续的Promise链继续执行,可以这样做。所以对于代码promise(A).catch(f1).then(f2):首先会执行pr......
  • 手写Word2vec算法实现
    1.语料下载:https://dumps.wikimedia.org/zhwiki/latest/zhwiki-latest-pages-articles.xml.bz2【中文维基百科语料】2.语料处理(1)提取数据集的文本下载的数据集无法直接使用,需要提取出文本信息。安装python库:pipinstallnumpypipinstallscipypipinstallgensimp......
  • JavaScript Promise Time Limit Function All In One
    JavaScriptPromiseTimeLimitFunctionAllInOneLeetCode2637.PromiseTimeLimiterrorsfunctiontimeLimit(fn:Fn,t:number):Fn{returnasyncfunction(...args){//letbegin=Date.now();letbegin=performance.now();letresult=......