重构同步和异步方法实现
假设我们有一个抽象类,该类具有一种抽象方法,可以在同步和异步变体中使用。
abstract class Base
{
abstract do(): number | Promise<number>;
}
现在,我创建了两个班级的孩子以进行同步和异步用法:
class SyncBase extends Base
{
do(): number
{
console.log('Start');
/* Sync-class specific code */
let result = 5;
console.log('End');
return result;
}
}
class AsyncBase extends Base
{
async do()
{
console.log('Start');
/* Async-class specific code */
let result = await /* ... */;
console.log('End');
return result;
}
}
如您所见,我在特定于类的代码之前和之后重复代码。
有没有办法重构此代码,所以我只编写一次之前的代码,而不是重复自己?
Let's say we have an abstract class which has an abstract method that can be use both in sync and async variants.
abstract class Base
{
abstract do(): number | Promise<number>;
}
Now I create two children of this class for sync and async usage:
class SyncBase extends Base
{
do(): number
{
console.log('Start');
/* Sync-class specific code */
let result = 5;
console.log('End');
return result;
}
}
class AsyncBase extends Base
{
async do()
{
console.log('Start');
/* Async-class specific code */
let result = await /* ... */;
console.log('End');
return result;
}
}
As you can see, I repeat the code before and after class specific code.
Is there a way to refactor this code so I only write before-after code once and not repeat myself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
摘要应该是
do
函数结果的逻辑。和do
函数将处理您的重复逻辑:我的建议:不要混合同步和异步返回类型(
numberm | promise&lt; number&gt;
),只需返回Promise&lt ; number&gt;
和getResult
和do
将始终是async
始终。The abstract should be the logic for the result of
do
function. Anddo
function will handle your duplicated logic:My recommendation: Don't mix sync and async return type (
number | Promise<number>
), just returnPromise<number>
andgetResult
anddo
will beasync
function always.