JS 链式调用与流程控制

357 阅读1分钟

JS 链式调用与流程控制

实现要求:

  • 能链式调用,执行 eatrun 等反复
  • 能控制程序调用时机(休眠),执行 sleep 时暂停若干秒后再执行
  • 同步函数在同一个执行栈中执行

class Person {
    constructor() {
        this.tasks = []
        setTimeout(() => {
            this.next()
        }, 0);
    }
    next() {
        if (this.tasks.length) {
            const fn = this.tasks.shift()
            fn()
        }
    }
    eat() {
        const fn = () => {
            console.log('eat')
            this.next()
        }
        this.tasks.push(fn)
        return this
    }
    run() {
        const fn = () => {
            console.log('run')
            this.next()
        }
        this.tasks.push(fn)
        return this
    }
    sleep(seconds) {
        const fn = () => {
            console.log('sleep')
            setTimeout(() => {
                this.next()
            }, seconds * 1000)
        }
        this.tasks.push(fn)
        return this
    }
}

const person = new Person()
person.eat().run().sleep(2).eat().sleep(2).run()