这是我所拥有的:
ngOnInit() {
this._addServ.getDefaultAddress().subscribe((res)=>{
if(res.status){
//I need these next two functions to finish their async API requests
//before selectNormalDelivery is called
this.selectShippingAddress();
this.selectBillingAddress();
this.selectNormalDelivery();
}
})
}
我需要selectShippingAddress
和selectBillingAddress
完成他们的通话,然后才能调用selectNormalDelivery
。我该怎么做?我不想将它们转换为Promise,因为它们在其他时间被称为无需链接。这涉及到.then
吗?
这是这些功能的代码:
selectShippingAddress(){
this.addressService.setShippingAddresses(this.cartService.shippingAddress.address_id).subscribe((res) => {
console.log('Set shipping address!')
console.log(res);
}, err => {
console.log('Failed to set shipping address')
console.log(err);
})
}
selectBillingAddress(){
this.addressService.setPaymentAddresses(this.cartService.billingAddress.address_id).subscribe((res) => {
console.log('Set billing address!')
console.log(res);
}, err => {
console.log('Failed to set billing address')
console.log(err);
})
}
如果尝试使用.then
,则会收到错误Property 'then' does not exist on type 'void'.
,这很有意义,因为我没有尝试返回任何东西,我只需要他们为API来完成调用。
建议?
ngOnInit() {
this._addServ.getDefaultAddress().subscribe((res)=>{
if(res.status){
Promise.all(this.selectShippingAddress(),this.selectBillingAddress()).then((results /* array of results */) => {
this.selectNormalDelivery();
}).catch(() => {
//one of the promises rejected
})
}
})
}
和
selectShippingAddress(){
return new Promise((resolve, reject) => {
this.addressService.setShippingAddresses(this.cartService.shippingAddress.address_id).subscribe((res) => {
resolve(res);
}, err => {
reject(err);
});
})
}
selectBillingAddress与setShippingAddresses类似