基本上我调用了返回Promises的不同SQL存储过程。通常这些将以随机顺序开始/结束,因为它们是异步的。我需要控制每个程序的调用顺序。
我尝试在callCustomerIUD承诺上使用.then()
,但this._dataService.customerIUD(...).then(...)
在callCustFieldIUD()
之后才会运行,因此customerFieldIUD
获取this.key
为{{{} 1}}。
undefined
我考虑过Observables,我可以在这种情况下使用它们吗?
以下是我的saveChanges(record) {
this.callCustomerIUD(record);
this.callCustFieldIUD();
}
callCustomerIUD(record): Promise<any>{
return this._dataService
.customerIUD(...)
.then(data => {
//THIS KEY IS NEEDED FOR customerFieldIUD
this.key = data[data.length-1].CustomerKey;
}, error => {
console.log(error);
});
}
callCustFieldIUD() : Promise<any>{
//USES KEY FROM customerIUD
this.fillCustomerField(this.key);
return this._dataService.customerFieldIUD(...);
}
方法参考。这些应该是Observables而不是Promises吗?
data.service.ts
答案 0 :(得分:1)
是的,在这种情况下,可观察量会很棒
saveChanges(record) {
this.callCustomerIUD(record).take(1).subscribe((data: any) => {
// Observables can be subscribed to, like a .then() on a promise
// data will be the response from the http call
this.callCustFieldIUD(data).take(1).subscribe();
});
}
callCustomerIUD(record): Observable<any>{
return this._dataService.customerIUD(...)
}
callCustFieldIUD(data: any) : Observable<any>{
//USES KEY FROM customerIUD
this.fillCustomerField(this.key);
return this._dataService.customerFieldIUD(...);
}
在服务中
customerIUD(data: any) : Observable<any>{
return this.fooHttp.postData(...).map((res: any) => {
return res.json();
});
}
customerFieldIUD(data: any) : Observable<any>{
return this.fooHttp.postData(...).map((res: any) => {
return res.json();
});
}
因为callCustFieldIUD()函数在subscribe()内部被callCustomerIUD()函数返回的observable调用,所以它不会执行直到数据存在。
(这可能不是你需要的确切代码。我不确定什么时候会发生,但是通过订阅observable,你可以对函数调用时更加严格)
希望这有帮助
_______________编辑_________________________
我相信你也可以通过承诺实现这一点,只需要一个轻微的重构
saveChanges(record) {
this.callCustomerIUD(record);
}
callCustomerIUD(record): Promise<any>{
return this._dataService
.customerIUD(...)
.then(data => {
// Instead of setting an instance var here, pass it in to the callCustFieldIUD() function
this.callCustFieldIUD(data[data.length-1].CustomerKey);
}, error => {
console.log(error);
});
}
callCustFieldIUD(customerKey: any) : Promise<any>{
//USES KEY FROM customerIUD
this.fillCustomerField(this.key);
return this._dataService.customerFieldIUD(...);
}
答案 1 :(得分:1)
您的第一个版本不起作用的原因是因为您的程序在http请求正在进行时继续继续工作。解决方案是在设置了所需的密钥后强制执行callCustFieldIUD。如果您正在使用Observables,则会出现同样的问题并以类似的方式解决。
你应该可以这样做:
saveChanges(record) {
this.callCustomerIUD(record);
}
callCustomerIUD(record): Promise<any>{
return this._dataService
.customerIUD(...)
.then(data => {
//THIS KEY IS NEEDED FOR customerFieldIUD
this.key = data[data.length-1].CustomerKey;
// Call the method you need to execute after the key is guaranteed
// to be set
this.callCustFieldIUD();
}, error => {
console.log(error);
});
}