How is the best way to call a promise inside a foreach?
I have an array and need to send each item to RestFull API. But at the same time, I have to check if the response its true ( i have a counter 'errorSendPayment'). After all requests I wonder sending a boolean or Promise if I have one (or more) error.
How can I improve my code?
public sendPaymentValues(sale: any, session: string): Promise<boolean> {
const headers = this.getHeader();
// counter
let errorSendPayment = 0;
sale.data.list.forEach(payment=> {
this.http.post(`${api}payment/`, payment, headers)
.toPromise()
.then((result: any) => {
if (!result.sucess) {
errorSendPayment++;
}
})
.catch((response: HttpErrorResponse) => {
this.httpErrorResponseHandler(response);
});
});
const promise: Promise<boolean> = new Promise((resolve, reject) => {
if (errorSendPayment <= 0) {
resolve();
} else {
reject();
}
});
return promise;
}
Use
zipoperator of Observable to combine http call.And check if results has an error.
Then make a promise by calling
toPromise.Update If you are using higher than RxJS 5.5, import an operator.