模拟任务流程编排(nodejs)

实现一个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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值