lazyMan(prototype)

159 阅读1分钟

function Lazyman(name) {
    this.name = name;
    this.events = [];
    setTimeout(() => {
        this.clear();
    }, 100);
}


Lazyman.prototype.eat = function eat() {
    this.events.push({
        type: 'sync',
        fn: () => { console.log(this.name + " eat"); }
    })
    return this;
}

Lazyman.prototype.run = function run() {
    this.events.push({
        type: 'sync',
        fn: () => { console.log(this.name + " run"); }
    })
    return this;
}

Lazyman.prototype.sleep = function(t) {
    this.events.push({
        type: 'async',
        fn: () => {
            return new Promise((resolve) => {
                setTimeout(() => {
                    console.log(`${this.name} sleep ${t}s`);
                    resolve();
                }, t * 1000);
            });
        }
    });
    return this;
}

Lazyman.prototype.first = function(t) {
    this.events.push({
        type: 'async',
        first: true,
        fn: () => {
            return new Promise((resolve) => {
                setTimeout(() => {
                    console.log(`first ${t}s done`);
                    resolve();
                }, t * 1000, this);
            });
        }
    });

    return this;
}

Lazyman.prototype.clear = async function(t) {
    this.events = [...this.events.filter(o => o.first), ...this.events.filter(o => !o.first)];
    for (const item of this.events) {
        if (item.type === 'sync') {
            item.fn();
        } else {
            await item.fn();
        }
    }
}

const tom = new Lazyman('kevin');

tom.sleep(1).eat().run().sleep(2).eat().first(2);