シミュレーションタスクフロー編成(nodejs)
4856 ワード
TaskManを実装すると、
TaskMan('john')
/** output:
hi, I am john
*/
TaskMan('john').doSomething('go to work')
/** output:
hi, I am john
doSomething go to work
*/
TaskMan('john').sleep(3).doSomething('go to work')
/** output:
hi, I am john
sleeping...0
sleeping...1
doSomething go to work
*/
TaskMan('jianyong').doSomething('go to work').sleep(3).doSomething('go home').sleepFirst(5)
/** output:
sleep 5 first...
sleeping...0
sleeping...1
sleeping...2
sleeping...3
hi, I am jianyong
doSomething go to work
sleeping...0
sleeping...1
doSomething go home
*/
関数のキューによって達成できます.class _TaskMan {
constructor(name) {
this.tasks = []
this.name = name
this.tasks.push(() => {
console.log('hi, I am ' + this.name)
this.next()
})
setTimeout(() => this.next(), 0)
}
next() {
let fn = this.tasks.shift()
fn && fn()
}
doSomething(taskname) {
this.tasks.push(() => {
console.log('doSomething ' + taskname)
this.next()
})
return this
}
sleep(n) {
this.tasks.push(() => {
let counter = 0
let timer = setInterval(() => console.log('sleeping...' + counter++), 1*1000)
setTimeout(() => {
this.next()
clearTimeout(timer)
}, n*1000)
})
return this
}
sleepFirst(n) {
this.tasks.unshift(() => {
console.log(`sleep ${n} first...`)
let counter = 0
let timer = setInterval(() => console.log('sleeping...' + counter++), 1*1000)
setTimeout(() => {
this.next()
clearTimeout(timer)
}, n*1000)
})
return this
}
}
function TaskMan(name) {
return new _TaskMan(name)
}
//TaskMan('john')
//TaskMan('john').doSomething('go to work')
//TaskMan('john').sleep(3).doSomething('go to work')
//TaskMan('jianyong').doSomething('go to work').sleep(3).doSomething('go home').sleepFirst(5)