I was working on a project that full of callbacks in codes, and the project is so complicated so that I can't refactor the basic structure.
So I created this class to help myself for organize async works, that should be execute in order but can not be decoupled because of callbacks should be execute inside the works.
在工作中我需要接受一个项目, 在这个项目里有许多异步操作, 而这些异步操作 都通过回调函数来实现. 因为这个项目比较复杂,我无法在短时间内去重构 这些基础结构.
而在这项目里我需要创建一些需要按顺序执行的步骤, 但这些步骤里有异步操作, 需要在执行回调函数时才能去调用下一步, 导致无法将这些步骤相互解耦. 因此我创建了这个类,来帮我管理这些工作步骤.
Create your async work as follow, receiving a AsyncWorkflow parameter so that you can call workflow.next() or workflow.interrupt() when this work finished or failed.
void anAsyncWork(AsyncWorkflow workflow, Object otherParam) {
doSomething();
doAsyncOperation(new Callback() {
if(isFailed) {
workflow.interrupt();
}
doAfterAsyncOperation();
workflow.next()
})
}
And then you could organize and execute your works like this.
void executeAsyncWorks() {
AsyncWorkflow
.getBuilder()
.append((workflow)-> anAsyncWork(workflow, otherParam))
.append(this::workWithoutOtherParam)
.run()
}