前端面试经典Promise理解与总结

Promise作为面试中的经典考题,我们一定要深刻学习和理解它! Promise有什么用呢?答:我们拿它解决异步回调问题。

概念

异步回调的一个很大的问题在于callback hell也就是“回调地狱”。多层嵌套回调函数,严重影响代码规范。Promise实际上是把回调函数从doSomething函数中提取到了后面的then()方法里,从而防止多重嵌套。一个Promise对象表示目前还不可用但是未来某个节点可以被解析的值,这个值要么被解析成功,要么失败抛出异常。它允许我们以同步的方式编写异步代码。

使用方法

Promise的构造函数用来构造一个Promise对象,其中入参匿名函数中resolve和reject这两个也都是函数。如果resolve执行了,则出发Promise.then中成功的回调函数,如果reject执行了,则触发了promise.then中拒绝的回调函数。

一个Promise对象一开始的值是pending准备状态,执行了resolve()后,Promise对象的状态值变为onFulfilled,执行了reject()后,状态值变为onRejected。Promise对象的状态值一旦确定,就不会再改变。

异常捕获

promise有两种异常捕获方式,一个是then中的reject,另一个是catch()方法。

then中的reject方法捕获异常

无法捕获当前then中抛出的异常

var promise = Promise.resolve();
promise.then(()=>{
    throw new Error("BOOM!");
}).then((success)=>{
    console.log(success);
}, (error)=>{
    console.log(error);
});
复制代码

catch捕获异常

catch不仅能捕获then中抛出的异常,还能捕获前面promise抛出的异常,所以建议使用catch方法。

var promise = Promise.reject("Boom!");
promise.then(()=>{
    return "success";
}).then((success) => {
    console.log(success);
    throw new Error("Another Boom!");
}).catch((error) => {
    console.log(error); //BOOM!
});
复制代码

手写Promise
基础篇-小试牛刀

首先来看基础版的代码,可以实现简单的同步代码,这一步是必须要能够写出来的。

// 首先要明确Promise是一个类,所以我们用class声明。
// 其次,构造函数中接收一个executor,它有两个参数,一个是resolve,一个是reject
// 这里要注意,resolve和reject都是函数
class Promise(){
    // 构造函数(入参是执行器,包括resolve和reject两个函数)
    constructor(executor){
        // 必要的初始化,这里用到状态,值和原因三个变量
        this.state = 'pending';
        this.value = undefined;
        this.reason = undefined;
        // 定义成功函数,入参是value
        let resolve = value => {
            // 首先要判断state是否为等待态,如果不是则不做任何处理
            if(this.state === 'pending'){
                // 修改状态
                this.state = 'fulfilled';
                // 更新值
                this.value = value;
            }
        };
        // 定义失败函数,入参是失败原因
        let reject = reason => {
            // 同样的逻辑
            if(this.state === 'pending'){
                this.state = 'rejected';
                this.reason = reason;
            }
        };
        // 这是promise对象的的主逻辑,执行executor,如果执行器出错,则捕获错误后执行reject函数
        try{
            executor(resolve, reject); 
        }catch(err){
            reject(err);
        }
    }
    // 定义Promise的then函数
    // then方法接收两个参数,如果状态为fulfilled,执行onFulfilled
    // 如果状态为rejected,则执行onRejected
    then(onFulfilled, onRejected){
        if(this.state === 'fulfilled'){
            onFulfilled(this.value);
        };
        if(this.state === 'rejected'){
            onRejected(this.reason);
        };
    }
}
复制代码

进阶篇 解决异步实现

class Promise{
    constructor(executor){
        this.state = 'pending';
        this.value = undefined;
        this.reason = undefined;
        // 成功回调函数数组和失败回调函数数组
        this.onResolveCallbacks = [];
        this.onRejectedCallbacks = [];
        let resolve = value => {
            if(this.state === 'pending'){
                this.state = 'fulfilled';
                this.value = value;
                // 成功的话遍历成功回调函数数组然后执行这些函数
                this.onResolvedCallbacks.forEach(fn=>fn());
            }
        };
        let reject = reason => {
            if(this.state === 'pending'){
                this.state = 'rejected';
                this.reason = reason;
                // 失败的话遍历失败回调函数数组然后执行这些函数
                this.onRejectedCallbacks.forEach(fn=>fn());
            }
        };
        try{
            executor(resolve,reject)
        }catch(err){
            reject(err);
        }
        then(onFulfilled, onRejected){
            if(this.state === 'fulfilled'){
                onFulfilled(this.value);
            }
            if(this.state === 'rejected'){
                onRejected(this.reason);
            }
            // 当状态为等待态时,我们要将成功/失败的回调函数加入到对应的数组中
            if(this.state === 'pending'){
                // onFulfilled传入到成功数组
                this.onResolvedCallbacks.push(()=>{
                    onFulfilled(this.value);
                })
                // onRejected传入到成功数组
                this.onRejectedCallbacks.push(()=>{
                    onRejeced(this.reason);
                })
            }
        }
    }
}
复制代码

威力加强版 解决链式调用

class Promise{
    constructor(executor){
        this.state = 'pending';
        this.value = undefined;
        this.reason = undefined;
        this.onResolvedCallbacks = [];
        this.onRejectedCallbacks = [];
        let resolve = value => {
            if(this.state === 'pending'){
                this.state = 'fulfilled';
                this.value = value;
                this.onResolvedCallbacks.forEach(fn=>fn());
            }
        };
        let reject = reason => {
            if(this.state === 'pending'){
                this.state = 'rejected';
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn=>fn());
            }
        };
        try{
            executor(resolve,reject);
        }catch(err){
            reject(err);
        }
    }
    then(onFulfilled, onRejected){
        let promise2 = new Promise((resolve,reject) => {
            if(this.state === 'fulfilled'){
               let x = onFulfilled(this.value); 
               resolvePromise(promise2, x, resolve, reject);
            };
            if(this.state === 'rejected'){
                let x = onRejected(this.reason);
                resolvePromise(promise2, x, resolve, reject);
            };
            if(this.state === 'pending'){
                this.onResolvedCallbacks.push(()=> {
                    let x = onFulfilled(this.value);
                    resolvePromise(promise2, x, resolve, reject);
                })
                this.onRejectedCallbacks.push(()=>{
                    let x = onRejected(this.reason);
                    resolvePromise(promise2, x, resolve, reject);
                })
            };
        });
        return promise2;
    }
    function resolvePromise(promise2, x, resolve, reject){
        if(x === promise2){
            return reject(new TypeError('Chaining cycle detected for promise');
        }
        let called;
        if(x != null && (typeof x === 'object' || typeof x === 'function')){
            try{
                let then = x.then;
                if(typeof then === 'function'){
                    then.call(x, y=>{
                        if(called){
                            return;
                        }
                        called = true;
                        resolvePromise(promise2,y,resolve,reject);
                    }, err => {
                        if(called) return;
                        called = true;
                        reject(err);
                    })
                }else{
                    resolve(x);
                }
            }catch(e){
                if(called) return;
                called = true;
                reject(e);
            }
        }else{
            resolve(x);
        }
    }
}
复制代码

有想了解更多的小伙伴可以加Q群链接里面看一下,应该对你们能够有所帮助。里面有许多学习资料和面试文档 以及免费的进阶技术分享。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355