这是我的成长之路:回调、promise、async/await。我记得一个模式——流畅的构建器,看起来更像解释器。我想将 async/await 与解释器混合。是否可以?我觉得不可能。但我可以准确地定义原因。 我有:
after(async () => {
await shellContainer.uninstall()
await shellContainer.dispose()
})
我感兴趣的是:
after(async () => {
await shellContainer
.uninstall()
.dispose()
})
问候。
最佳答案
为了分离关注点,您可以引入专用的 builder它实现了流畅的界面。
这样你只需要从最终的 build
返回一个 promise 方法,让事情变得简单很多。
以下是一个相当粗糙但实用的示例:
class ShellContainer
{
uninstall() {
return new Promise(resolve => {
setTimeout(() => {
console.log('uninstalled');
resolve();
}, 400 + Math.random() * 600);
});
}
dispose() {
return new Promise(resolve => {
setTimeout(() => {
console.log('disposed');
resolve();
}, 400 + Math.random() * 600);
});
}
}
class ShellContainerBuilder
{
container;
plan;
constructor() {
this.reset();
}
reset() {
this.container = new ShellContainer();
this.plan = () => Promise.resolve();
}
stage(op) {
this.plan = ((prev) => () => prev().then(op))(this.plan);
}
uninstall() {
this.stage(() => this.container.uninstall());
return this;
}
dispose() {
this.stage(() => this.container.dispose());
return this;
}
build() {
return this.plan().then(() => this.container);
}
}
(async () => {
console.log('starting w/o builder:');
const shellContainer1 = new ShellContainer();
await shellContainer1.uninstall();
await shellContainer1.dispose();
console.log('w/o builder done.');
console.log('starting w/ builder:');
const shellContainer2 = await (new ShellContainerBuilder()).uninstall().dispose().build();
console.log(shellContainer2);
console.log('w/ builder done.');
})();
关于javascript - 是否可能 Async Await - 流畅的构建器方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55061082/