美文网首页
手写promise(1)

手写promise(1)

作者: 路上灵魂的自由者 | 来源:发表于2019-07-16 14:52 被阅读0次

class Promise{

    constructor(excutorCallBack){

        this.status = 'pending'

        this.value = undefined;

        this.fulfilledAry = []; //管控,必须得then执行后才能执行resolveFn方法,成功要做的方法

        this.rejectedAry = []; //失败要做的方法

        // => 执行EXCUTOP

        let resolveFn = (result) =>{

            let timer = setTimeout(()=>{

                if(this.status !== 'pending') return;

                    clearTimeout(timer)

                    this.status = 'fulfilled';

                    this.value = result;

                    this.fulfilledAry.forEach(item=>item(this.value))

            },0)

        };

        let rejectFn = (reason) =>{

            let timer = setTimeout(()=>{

                clearTimeout(timer)

                if(this.status !== 'pending') return;

                this.status = 'rejected';

                this.value = reason;

                this.rejectedAry.forEach((item)=>item(this.value))

            },0)

        }

        // => 执行EXCUTOP(异常捕获)

        try{

            excutorCallBack(resolveFn,rejectFn);

        } catch (err){

            // 有异常信息按照rejected状态信息处理

            rejectFn(err);

        }

    }

    then (fulfilledCallBack,rejectedCallBack) {

        this.fulfilledAry.push(fulfilledCallBack);

        this.rejectedAry.push(rejectedCallBack);

    }

}

module.exports = Promise;

相关文章

  • 手写 Promise 系列 --- 3

    在前两篇(手写 Promise 系列 --- 1)和(手写 Promise 系列 ---2) 中,达成了3个目标 ...

  • 手写Promise

    手写 Promise 我们会通过手写一个符合 Promise/A+ 规范的 Promise 来深入理解它,并且手写...

  • 手写基础 promise

    1. 前言 玩下吧 手写 promise,看看能写成啥样 2. promise 基础结构 3. 手写`promi...

  • 手写promise(1)

    class Promise{ constructor(excutorCallBack){ this.status ...

  • 2020前端基础大纲(20200202)

    2020前端基础大纲1、promise 原理 promise.all 可以手写出大概。(async awa...

  • 手写 Promise 系列 --- 1

    Promise 是 ES6 推出的用于解决callback嵌套层级太深问题的一种异步方案. 基本使用如下. 先不考...

  • 手写 Promise 系列 --- 2

    在上一篇 手写 Promise 系列 --- 1 中,我们达成了两个目标 Promise 实例的状态改变 [✅] ...

  • 手写Promise

    $ 正常的promise用法   $ 手写的Promise   # 测试可行性

  • 手写promise

    手写promise 带大家手写一个 promis。在手写之前我会先简单介绍一下为什么要使用promise、prom...

  • 前端手写算法题

    1、深拷贝deepCopy 2、对象扁平化 3、数组扁平化 4、手写Promise 5、promise.all方法...

网友评论

      本文标题:手写promise(1)

      本文链接:https://www.haomeiwen.com/subject/uiyayqtx.html