我正在实现这个 button在我的应用程序中。
在我的按钮组件中我有:
@Input() callback: () => Promise<null>;
onClick() {
this.spinnerService.show();
this.callback().then(() => {
this.spinnerService.hide();
}, () => {
this.spinnerService.hide();
});
}
(我不使用 async/await 因为“技术负责人”不想要我)
组件模板:
<my-button [callback]="doSomething">
</my-button>
当我将这种代码传递给组件的输入时,一切正常:
doSomething = () => {
return myService.doSomething()
.toPromise()
.then((response) => console.log('promise resolved'));
}
但是我需要提前中断这个函数:
doSomething() {
if (condition) {
return;
}
return myService.doSomething()
.toPromise()
.then((response) => console.log('promise resolved'));
}
我明白了
ERROR TypeError: Cannot read property 'then' of undefined
我试过用同样的结果强制 promise
if (condition) {
return Promise.resolve(null);
// or
return new Promise((resolve) => { resolve(null); });
}
最佳答案
对于这个输入
@Input() callback: () => Promise<null>;
不能保证它被赋予了正确的值。额外检查是否 callback
指定应添加。
一个更安全的管理方法是使用 async
在这些地方发挥作用是因为它们始终使用 promise:
async onClick() {
this.spinnerService.show();
try {
if (this.callback)
await this.callback()
} finally {
this.spinnerService.hide();
}
}
doSomething
应该无条件地返回一个 promise ,这也可以用 async
来解决。 :
async doSomething() {
if (!condition)
return myService.doSomething().toPromise();
}
如果async
由于某些原因不能使用函数(虽然没有好的函数,因为它们符合规范,是 TypeScript 中的一等公民),promises 应该在函数中一致地处理(也有助于测试)。 doSomething
类型不正确,这会导致不正确的函数返回。应该是:
onClick(): Promise<void> {
this.spinnerService.show();
return Promise.resolve(this.callback ? this.callback() : undefined)
.catch(() => {})
.then(() => {
this.spinnerService.hide();
});
}
和
doSomething(): Promise<void> {
if (condition) {
return Promise.resolve();
}
return myService.doSomething().toPromise();
}
以及 callback
的类型将是 Promise<void>
, 不是 Promise<null>
.
常规(非箭头)doSomething
方法应绑定(bind)到 this
在构造函数中。
关于javascript - 返回空洞的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302235/