【发布时间】:2020-07-05 04:21:02
【问题描述】:
我正在将一些基于 Q-promise 的 typescript 代码转换为 ES6-promises。
在某个时刻,我使用了 Q.defer,在我的迁移中,我只是将 defer 重写为 ES6 承诺,就像在此评论中解释的那样: https://stackoverflow.com/a/49825137/13116953
如果可能的话,我试图摆脱这种延迟方法,并正在寻找替代解决方案。
我提出问题的原因是:
- 一般来说,延迟承诺被视为一种反模式
- 想知道这种情况是否是少数真正将延迟作为唯一方法的场景之一
这是我的场景:
// app start, this is my low level API
init() {
commService.subscribe("myRecordId", {
onRecordAdd: this.onAdd
});
}
...
private _myRecord: MyRecordObj | null = null;
private _recordReceivedDef = newDeferred(); // was Q.defer()
// callback will be called when record is received
private readonly onAdd = (recordObj: MyRecordObj) => {
this._myRecord = recordObj;
this._recordReceivedDef.resolve(recordObj);
}
...
// here's my async code that requires the deferred
public readonly doStuff = async () => {
// ...
const myRec = await this._recordReceivedDef.promise;
// use myRef
}
我的问题是:有什么办法可以摆脱这种延迟?
我正在考虑当_myRecord 更改时可以解决的问题,但不知道该怎么做。
旁注: 我在我们应用程序的其他部分使用 MobX,因此拥有
await when(() => this._myRecord); // of course _myRecord must be @observable
会很方便,但不幸的是我不能在这段特定的代码中使用 MobX。
非常感谢任何帮助。
非常感谢!
【问题讨论】:
标签: javascript typescript promise es6-promise q