Skip to content

Instantly share code, notes, and snippets.

@zyf0330
Created November 23, 2018 03:00
Embed
What would you like to do?
class TaskList {
constructor(tasks) {
this.tasks = tasks
this.promise = null
this.index = 0
this.fowarding = false
}
async start() {
this.fowarding = true
let promise = this.promise = Promise.resolve()
this.tasks.forEach((task) => {
promise = promise.then((...args) => {
this.index++
if (this.forwarding = false) {
return args
} else {
return task.forward(...args)
}
})
})
return promise
}
cancel() {
this.fowarding = false
let promise = this.promise
this.tasks.slice(0, this.index).forEach((task) => {
if (!task.needCancel) {
return
}
promise = promise.then((...args) => {
return task.backward(...args)
})
})
return promise
}
}
let a = 1, b = 2
const tl = new TaskList([
{
forward: async () => {
a = 2
return new Promise((res) => {
setTimeout(() => {
res('finish')
}, 10000)
})
},
backward: async () => {
a = 1
},
needCancel: true,
},
{
forward: async () => {
b = 8
},
backward: async () => {
b = 2
},
needCancel: false,
},
])
tl.start().then(() => {
console.log('in start', a, b)
})
setTimeout(() => {
console.log('waiting', a, b)
}, 200)
setTimeout(() => {
tl.cancel().then(() => {
console.log('in cancel', a, b)
})
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment