Dremor
Dremor

Reputation: 831

Observable from a Promise with nested Promise

I have a service that call the new Xrm.WebApi endpoint.

This endpoint return a Promise, which have a nested Promise "json" (documentation), which allows to get the json returned by the service.

From this json I extract some data using the "parseData" method, which return it as an Array of objects.

I want to return an Observable<MyObject[]>, but all I can get for now is an Observable<Promise<MyObject[]>>.

My current code looks like the following :

return from(Xrm.WebApi.online.execute(crmRequest).then(
      result => {
        if (result.ok) {
          return result.json().then(json => {
            let res : MyObject[]= this.parseData(json);
            return res;
          }); 
        }
      },
      error => {
        throw error;
      }
    ));

Environment:
- Angular 8.2
- RxJs 6.4

Upvotes: 0

Views: 768

Answers (2)

frido
frido

Reputation: 14139

Use from to convert your first Promise to an Observable and use switchMap to map to an inner Promise. filter is used to only emit results that are ok and map is used to map to your desired output. This Observable will error when the first or second Promise errored.

return from(Xrm.WebApi.online.execute(crmRequest)).pipe(
  filter(result => result.ok),
  switchMap(result => result.json()),
  map(json => this.parseData(json) as MyObject[]),
)

For more info read my response at: Convert Promise to Observable

Upvotes: 1

Dremor
Dremor

Reputation: 831

After some tries I got this working with the following code :

return new Observable(observer => {
        Xrm.WebApi.online.execute(crmRequest).then(
          result => {
            if (result.ok) {
              result.json().then(json => {
                let res : MyObject[]= this.parseData(json);
                observer.next(res);
                observer.complete();
              });
            }
          },
          error => {
            observer.error(error);
          }
        );
      });

It create an Observable with a custom Observer, and trigger the observer .next() in the nested Promise in order to return the right data.

Upvotes: 0

Related Questions