【发布时间】:2018-08-24 10:16:46
【问题描述】:
我正在我的应用中实现这个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
我试过强制一个具有相同结果的承诺
if (condition) {
return Promise.resolve(null);
// or
return new Promise((resolve) => { resolve(null); });
}
【问题讨论】:
-
哪个“then”属性导致问题?
-
@Sharcoux,然后来自按钮组件。第一个代码块
-
(I don't use async / await because the "tech lead" doesn't want me too)StackOverflow 无法帮助您解决公司间的自负 ;) -
Promise 不是这里的问题。您正在关注位于受控代码之前的 if(condition)。
-
多么奇怪。我尝试了类似的方法,并且效果很好。您是否尝试检查满足条件时 doSomething() 方法真正返回的内容?我的意思是,你没有任何破坏 Promise.resolve 的库,不是吗?你能做到这一点,看看它返回什么?
console.log(this.callback())在你的onClick()方法中
标签: javascript angular typescript promise