Giter VIP home page Giter VIP logo

Comments (4)

EmilyYoung71415 avatar EmilyYoung71415 commented on June 1, 2024 1

可以把任务看成三类:sleepFirst(微任务)、sayname(constructor任务)、eat&sleep(宏任务)
整个过程就是: 先串行执行微任务,再执行constructor任务,最后串行执行宏任务

class LazyMan {
    constructor(name) {
        this.name = name;
        this.microTaskList = []; // 微任务
        this.macroTaskList = []; // 宏任务

        // Promise.resolve()使得先注册回调 再执行constructor
        Promise.resolve()
        .then(() => this.runInOrder(this.microTaskList))
        .then(() => this.sayHello())
        .then(() => this.runInOrder(this.macroTaskList));
    }
    sleepFirst(time) {
        this.taskListAdd({type: 'micro', funcType: 'sleepFirst', params: {time}});
        return this;
    }
    sleep(time) {
        this.taskListAdd({type: 'macro', funcType: 'sleep', params: {time}});
        return this;
    }
    eat(food) {
        this.taskListAdd({type: 'macro', funcType: 'eat', params: {food}});
        return this;
    }
    sayHello() {
        console.log(`Hi This is ${this.name}`);
    }
    runInOrder(promiseArr) {
        return promiseArr.reduce(
            (prevPromise, nextPromise) => prevPromise.then(() => nextPromise()),
            Promise.resolve()
        );
    }
    taskListAdd({type, funcType, params}) {
        let func = () => {};
        switch (funcType) {
            case 'sleep':
            case 'sleepFirst':
                func = () => new Promise(resolve => {
                    setTimeout(() => {
                        console.log(`Wake up after ${params.time}`);
                        resolve();
                    }, params.time * 1000);
                });
                break;
            case 'eat':
                func = () => new Promise(resolve => {
                    console.log(`Eat ${params.food}~`);
                    resolve();
                });
                break;
            default:
                break;
        }

        this[`${type}TaskList`].push(func);
    }
}

from blog.

willxiao90 avatar willxiao90 commented on June 1, 2024 1

这是我想到的版本,看到这个题目,我没有自己去写任务队列,而是使用了系统级别的宏任务和微任务

class LazyMan {
  constructor(name) {
    this.name = name;
    setTimeout(() => {
      console.log("Hi! This is " + name);
    }, 0);
  }

  sleep(seconds) {
    const delay = seconds * 1000;
    const time = Date.now();
    while (Date.now() - time < delay) {
      // hu lu lu ~~
    }
    setTimeout(() => {
      console.log("wake up after " + seconds);
    }, 0);
    return this;
  }

  eat(something) {
    setTimeout(() => {
      console.log("eat " + something);
    }, 0);
    return this;
  }

  sleepFirst(seconds) {
    new Promise((resolve) => {
      const delay = seconds * 1000;
      const time = Date.now();
      while (Date.now() - time < delay) {
        // hu lu lu ~~
      }
      resolve();
    }).then(() => {
      console.log("wake up after " + seconds);
    });
    return this;
  }
}

function lazyMan(name) {
  return new LazyMan(name);
}

lazyMan("Hank").sleep(2).eat("dinner").sleepFirst(3);

from blog.

EmiyaYang avatar EmiyaYang commented on June 1, 2024

学习了

from blog.

think2011 avatar think2011 commented on June 1, 2024
function lazyMan (name) {
    const tasks = []
    const methods = {
        say(name) {
            tasks.push(() => console.log(`Hi! This is ${name}`))
            return this
        },
        eat(food) {
            tasks.push(() => console.log(`Eat ${food}`))
            return this
        }, 
        sleepFirst(time) {
            tasks.unshift(() => new Promise(resolve => setTimeout(resolve, time * 1000)))
            return this
        },  
        sleep(time) {
            tasks.push(() => new Promise(resolve => setTimeout(resolve, time * 1000)))
            return this;
        }
    }

    setTimeout(function run() {
        if(!tasks.length) return
        Promise.resolve(tasks.shift()()).then(run)
    }, 0)
    methods.say(name)

    return methods
}


// lazyMan('think2011').sleep(3).eat('supper')
// lazyMan('think2011').eat('dinner').eat('supper')
lazyMan('think2011').sleepFirst(3).eat('supper')

我来一个不使用 class 的

from blog.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.