如何在ng2中实现此承诺方案?
export class MySpecializedClass
{
myObject;
constructor(
private myService: MyService
)
{
this.myObject = new MyObject();
}
buildMyObject()
{
this.builderMethod1();
this.builderMethod2();
}
builderMethod1()
{
this.myService.getData1()
.then(response => this.myObject.Prop1 = response.Prop1 )
}
builderMethod2()
{
this.myService.getData2()
.then(response => this.myObject.Prop2 = response.Prop2 )
}
}
export class MyConsumerClass
{
myObect;
getMyObject()
{
this.myObject = new MySpecializedClass().buildMyObject().myObject;
}
}
问题在于,在以下代码行中,在构建builderMethod1()和builderMethod2()之前,不应引用myObject。
MyConsumerClass.getMyObject().myObject
我希望builderMethod1()和builderMethod2()同时运行,这就是为什么它们没有在then()中链接的原因。我怎么能用Promises实现这个场景?或者Observables或其他方法能提供更好的解决方案吗?
答案 0 :(得分:1)
就我个人而言,我发现async-await语法比链接更具可读性。也许你也会这样,这就是使用async-await做同样的事情:
export class MySpecializedClass
{
myObject : MyObject;
constructor(
private myService: MyService
)
{
this.myObject = new MyObject();
}
async buildMyObject()
{
const first = this.builderMethod1();
await this.builderMethod2();
await first;
return this.myObject;
}
async builderMethod1()
{
const response = await this.myService.getData1();
this.myObject.Prop1 = response.Prop1;
}
async builderMethod2()
{
const response = await this.myService.getData2();
this.myObject.Prop2 = response.Prop2;
}
}
export class MyConsumerClass
{
myObject;
async getMyObject()
{
this.myObject = await new MySpecializedClass(new MyService()).buildMyObject()
}
}
答案 1 :(得分:0)
你可以回复承诺:
builderMethod2()
{
return this.myService.getData2()
.then(response => {
this.myObject.Prop2 = response.Prop2;
return response.Prop2;
})
}
答案 2 :(得分:0)
您可以在promise和Observable中执行此操作。我更喜欢可观察的,因为它有比承诺更多的选择
<强>许强>
在承诺的情况下,您需要返回承诺/不同。但在你的情况下,你没有返回任何东西,当你说.then
它解决了承诺
导出类MySpecializedClass { myObject的;
constructor(
private myService: MyService
)
{
this.myObject = new MyObject();
}
buildMyObject()
{
var diff = differed // find out exact differed object
return diff.all(this.builderMethod1(), this.builderMethod2());
}
builderMethod1()
{
return this.myService.getData1()
.then(response => this.myObject.Prop1 = response.Prop1 )
}
builderMethod2()
{
return this.myService.getData2()
.then(response => this.myObject.Prop2 = response.Prop2 )
}
}
导出类MyConsumerClass { myObect;
getMyObject()
{
this.myObject = new MySpecializedClass().buildMyObject().then (() => {
myObject;
}
}
}
<强>可观察强>
如果是可观察的,你可以Observable.merger
,Observable.formJoin
等加入你的2个观察者并订阅它们