博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
promise封装
阅读量:3903 次
发布时间:2019-05-23

本文共 1453 字,大约阅读时间需要 4 分钟。

class MyPromise{        constructor(callback){            this.status = 'pendding';            this.result = null;            this.err = null;            this.resolveFn = null;            this.rejectFn = null;            this.resolve = function(val){                if(this.status === 'pendding'){                    this.status = 'resolve';                    this.result = val;                    this.resolveFn && this.resolveFn(this.result);                }            }            this.reject = function(err){                if(this.status === 'pendding'){                    this.status = 'reject';                    this.err = err;                    this.rejectFn && this.rejectFn(this.err);                }            }            callback(this.resolve.bind(this),this.reject.bind(this));          }        then(callback){            if(this.status === 'resolve' ){                callback(this.result);            }else{                this.resolveFn = callback;            }            return this;        }        catch(callback){            if(this.status === 'reject' ){                callback(this.err);            }else{                this.rejectFn = callback;            }        }      }

 调用

let p = new MyPromise((resolve,reject) => {        setTimeout(() => {            resolve(123);            reject(456);          },1000)      })    p.then(res => {        console.log(res);    }).catch(err => {        console.log(err);    })

 

转载地址:http://roven.baihongyu.com/

你可能感兴趣的文章
467. 环绕字符串中唯一的子字符串
查看>>
468. 验证IP地址
查看>>
474. 一和零
查看>>
486. 预测赢家
查看>>
494. 目标和
查看>>
520. 检测大写字母
查看>>
数据处理和训练模型的技巧
查看>>
vb 中如何做同步 异步?
查看>>
geturl
查看>>
李建忠,设计模式教程.笔记061220
查看>>
李建忠,设计模式教程.笔记061221
查看>>
关于sizeof
查看>>
windows 核心编程笔记.070301
查看>>
WINDOWS核心编程笔记 070303
查看>>
终于解决了交叉表左上角,每页都显示的问题.
查看>>
windows核心编程 070309
查看>>
哈,又解决水晶报表的一个难题
查看>>
VC Ini文件处理
查看>>
一直误解sql事务的用法.
查看>>
转:利用C#实现分布式数据库查询
查看>>