前端面试题 - 如何实现 promise?
前端面试题 - 如何实现 promise?
通过构造函数生成一个 promise 对象,该构造函数有一个延时函数参数
通过 promise.then()或 promise.catch()方法实现结果获取
then 函数和 catch 函数可以链式调用
复制代码
通俗易懂的前端面试题网站: https://www.front-interview.com
本文字数:594 字
阅读完需:约 2 分钟
通过构造函数生成一个 promise 对象,该构造函数有一个延时函数参数
通过 promise.then()或 promise.catch()方法实现结果获取
then 函数和 catch 函数可以链式调用
function MyPromise(func) { this.status = 'pending'; this.res = ''; this.thenCbs = []; this.catchCbs = []; const resolve = (data) => { this.status = 'fulfilled'; this.res = data; this.thenCbs.forEach(cb => { cb(this.res); }); } const reject = (data) => { this.status = 'rejected'; this.res = data; this.catchCbs.forEach(cb => { cb(this.res); }); } this.then = function (cb) { if (this.status == 'pending') { this.thenCbs.push(cb); } if (this.status == 'fulfilled') { var res = cb(this.res) } return this; } this.catch = function (cb) { if (this.status == 'pending') { this.catchCbs.push(cb) } if (this.status == 'rejected') { var res = cb(this.res) } return this; } func(resolve, reject)}
通俗易懂的前端面试题网站: https://www.front-interview.com
还未添加个人签名 2023-10-07 加入
还未添加个人简介

促进软件开发及相关领域知识与创新的传播
京公网安备 11010502039052号 | 产品资质

评论