Print

前端链式调用和事件循环


作者: 文章来源:

本文原地址:https://www.mimiwuqi.com/webqianduan/196009.html

我们通过一道题目来理解前端链式调用和事件循环。

实现一个方法,支持链式调用:

lazyman.lazy('Lisa').sleep(3).sleepFirst(4).eat('lunch');
// 4s 后输出:Sleep Afater 4
// 输出:I'm Lisa
// 3s 后输出:Sleep After 3
// 输出:I'm eat lunch

解法

class LazyMan {
    callbacks = [];

    constructor() {
        this.next();
    }

    next() {
        setTimeout(() => {
            const firstFn = this.callbacks.shift();
            firstFn && firstFn();
        }, 0);
    }

    lazy(name) {
        this.callbacks.push(() => {
            console.log(`Hi, I'm ${name}`);
            this.next();
        });
        return this;
    }

    sleep(time) {
        this.callbacks.push(() => {
            setTimeout(() => {
                console.log(`Sleep after ${time}`);
                this.next();
            }, time * 1000);
        });
        return this;
    }

    sleepFirst(time) {
        this.callbacks.unshift(() => {
            setTimeout(() => {
                console.log(`Sleep after ${time}`);
                this.next();
            }, time * 1000);
        });
        return this;
    }

    eat(item) {
        this.callbacks.push(() => {
            console.log(`I am eat ${item}`);
            this.next();
        });
        return this;
    }
}

const lazyman = new LazyMan();
lazyman.lazy('Lisa').sleep(3).sleepFirst(4).eat('lunch');

题解分析

这个题目,首先要知道如何完成链式调用,就是设置一个类,类中声明的方法的结尾最后都会重新返回该类实例的引用,这样就能够链式调用了。

所以我们创建一个 LazyMan 的类。

接下来是如何保证顺序执行,那就是使用一个回调数组,每个函数调用后会检查一次回调是否为空,如果不为空,则继续执行。
同时为了保证第一次执行前,会先进行一遍所有函数的遍历,确认优先级,我们在 constructor 里面使用 setTimeout 进行创建一个微任务,这样会等 main 函数里的宏任务全部执行完,才会开始真正的函数执行。

所以这个题目的关键点:

更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/