Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

foo.print('happy').wait(3000).print('new').wait(3000).print('day')打印happy,3s后打印new,再过3s后打印day #1

Open
jiefancis opened this issue Apr 20, 2022 · 0 comments

Comments

@jiefancis
Copy link
Owner

我相信,不少人拿到这个题的时候,第一印象是:

  • 创建一个Chain类,有wait print方法,且这些方法返回当前对象(this)
  • 维护一个this._events栈,将wait print的操作记录下来
  • 通过promise + setTimeout的特性,实现wait效果
  • 通过promise的resolve实现链式方法的依次执行,代码如下
class Chain{
  constructor() {
    this._events = []
    this.run()
  }
  run() {
    Promise.resolve().then(() => {
       this._events.reduce((p,n) => p.then(n), Promise.resolve())
    })
  }
  wait(time) {
    let fn = () => new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, time)
    })
    this._events.push(fn)
    return this
  }
  print(str) {
    let fn = () => new Promise((resolve) => {
      console.log(str)
      resolve()
    })
    this._events.push(fn)
    return this
  }
}

var foo = new Chain()
foo.print('happy').wait(3000).print('new').wait(3000).print('day')
  • 进阶版
    上面的实现方式没有错,如果想要代码更加简洁点,还是可以再优化的,优化的方向是代码中逻辑体现出来的是每个方法执行结束返回的新的promise,再通过新promise.then的方式去执行下一个函数,异步的方式去管理任务的执行,所以:
class Chain{
  promise = Promise.resolve()
  wait(time) {
    this.promise = this.promise.then(() => new Promise(resolve => setTimeout(resolve, time)))
    return this
  }
  print(str) {
    this.promise = this.promise.then(() => console.log(str))
    return this
  }
}

var foo = new Chain()
foo.print('happy').wait(3000).print('new').wait(3000).print('day')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant