我有呼叫服务的功能
private callService() {
this.functionOne();
this.functionTwo();
this.functionThree();
}
private getOtherInfo() {
// pure sync here
this.getId(this.user['data']);
this.getType(this.name['data']);
}
我希望先运行callService
,然后再运行getOtherInfo
。
但是我发现代码无法达到第二个功能。
callService
中的函数有点像
private functionOne() {
this.user['loading'] = true;
this.service['user'].get().subscribe(data => {
this.user['data'] = data;
}
}
private functionTwo() {
this.name['loading'] = true;
this.service['name'].get().subscribe(data => {
this.name['data'] = data;
}
}
.....
因此我将功能更改为
private callService(): Promise<any> {
return Promise.resolve() => {
this.functionOne();
this.functionTwo();
this.functionThree();
});
}
在ngOnInit()
中,我致电
this.callService().then(()=> this.getOtherInfo());
但是仍然不能达到第二个功能。
答案 0 :(得分:1)
代码看起来不正确。 functionOne
,functionTwo
等实际上并没有返回承诺。他们实际上根本不返回任何东西。您拥有.subscribe
,但实际上从未对其做任何事情。如果将函数包装在一个Promise中并正确地解决了它们,那么您应该可以等待所有它们而没有任何问题:
示例:
private functionOne() {
return new Promise( (resolve, reject) => {
this.user['loading'] = true;
this.service['user'].get().subscribe(data => {
this.user['data'] = data;
resolve();
});
});
}
private functionTwo() {
return new Promise( (resolve, reject) => {
this.name['loading'] = true;
this.service['name'].get().subscribe(data => {
this.name['data'] = data;
resolve();
});
});
}
private callService(): Promise<any> {
return new Promise( async (resolve, reject) => {
await this.functionOne();
await this.functionTwo();
await this.functionThree();
});
});
这是一个如何构造它的示例(这个问题并不是特定于角度的)
function functionOne() {
return new Promise( (resolve, reject) => {
setTimeout( () => resolve('return from function 1'), 1000);
})
}
function functionTwo() {
return new Promise( (resolve, reject) => {
setTimeout( () => resolve('return from function 2'), 1000);
})
}
async function callAllFunctions() {
const result1 = await functionOne();
console.log(result1);
const result2 = await functionTwo();
console.log(result2);
}
callAllFunctions().then( () => console.log('finished'));
答案 1 :(得分:1)
所有这些都可以通过可观察的方式解决,而无需承诺...
您需要将三个功能更改为:
private functionOne() {
this.user['loading'] = true;
return this.service['user'].get();
}
private functionTwo() {
this.name['loading'] = true;
return this.service['name'].get();
}
,然后您的callService如下:
private callService(): Promise<any> {
forkJoin(
this.functionOne(),
this.functionTwo(),
this.functionThree()
).subscribe(([user, name, fnThreeData]) => {
this.user['data'] = user;
this.name['data'] = name;
//whatever with fnThreeData
this.getOtherInfo();
});
}
不要将承诺和其他东西混在一起,rxjs提供了您需要的所有功能。如果不购买rxjs,您将面临与angular的艰苦战斗。