Promises inside foreach in angular 4/typescript

210 Views Asked by At

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;
}
1

There are 1 best solutions below

1
zmag On
  1. Use zip operator of Observable to combine http call.

  2. And check if results has an error.

  3. Then make a promise by calling toPromise.

  4. Update If you are using higher than RxJS 5.5, import an operator.


import { zip } from 'rxjs';

public sendPaymentValues(sale: any, session: string): Promise<boolean> {
  const headers = this.getHeader();
  const obs$ = sale.data.list.map(payment => this.http.post(`${api}payment/`, payment, headers))

  return zip(...obs$).map(arr => arr.some(res => !res.success)).toPromise()
}