Skip to content

Instantly share code, notes, and snippets.

@Hahet
Last active November 16, 2020 07:07
Show Gist options
  • Save Hahet/b0aff01e48c3253356da7d296fbb8d0d to your computer and use it in GitHub Desktop.
Save Hahet/b0aff01e48c3253356da7d296fbb8d0d to your computer and use it in GitHub Desktop.
// 实现带异步任务的链式调用:chain.eat().sleep(5).work().eat().work().sleep(10)
// 链式调用:函数都 return this
// 链式调用时(同步过程),会将每个任务(函数)放到 队列中(tasks)
// 使用 start 函数异步开始执行第一个任务( next 函数第一次调用) 每一个任务执行完就 再调用 next 函数,next 会取出下一个任务出来执行
class Chaos {
constructor() {
this.tasks = []
const fn = () => {
console.log('chain start')
this.next()
}
this.tasks.push(fn)
}
start() {
// 启动调用
Promise.resolve().then(() => {
this.next()
})
return this
}
next() {
const fn = this.tasks.shift();
fn && fn()
}
sleep(n) {
const fn = () => {
console.log('sleep start')
setTimeout(() => {
console.log('sleep end')
this.next()
}, n * 1000)
}
this.tasks.push(fn)
return this
}
work() {
const fn = () => {
console.log('work')
this.next()
}
this.tasks.push(fn)
return this
}
eat() {
const fn = () => {
console.log('eat')
this.next()
}
this.tasks.push(fn)
return this
}
}
const chain = () => {
return new Chaos().start()
}
chain().eat().sleep(5).work().eat().work().sleep(10)
@Hahet
Copy link
Author

Hahet commented Nov 16, 2020

更简单的使用 promise 实现

class Chains {
  task = Promise.resolve()
  eat() {
    this.task = this.task.then(() => {
      console.log('eat')
    })
    return this
  }
  work() {
    this.task = this.task.then(() => {
      console.log('work')
    })
    return this
  }
  sleep(n) {
    this.task = this.task.then(() => {
      console.log('sleep start')
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log('sleep end')
          resolve()
        }, n * 1000)
      })
    })
    return this
  }
}
const chain = new Chains()
chain.eat().sleep(5).work().eat().work().sleep(10)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment