1
votes

This should be an easy solution but I cannot seem to put it together...

I have a function that returns a Promise and another one that returns Promise. I need to call the latter using the former's return value but I also need both values at the end of the transformation chain. I have read some documentation about mergeMap and forkJoin but I cannot seem to use them to get the result I need:

function getBlob(id: string): Promise<Blob>;
function blobToBase64(imageBlob: Blob): Promise<string>;

// ...


// This is what I tried but I getting Observables back after the forkJoin instead of the actual values
return Observable.fromPromise(getBlob(id))
  .map((blob) => return Observable.forkJoin([Observable.of(blob), Observable.fromPromise(blobToBase64)])
  // data[0] and data[1] are undefined but it looks like data is actually an Observable from forkJoin.
  .map((data) => console.log(`Here is ${data[0]} and ${data[1]}`);

Can anyone explain how to wind up with both the blob and the base64 value at the end?

1

1 Answers

5
votes

To create the blobToBase64 promise based on the result of the first promise, you can use an operator from the flatMap familly (mergeMap, switchMap, concatMap, etc.)

The simplest is mergeMap, it take an observable, and when it emits, it create a new observable based on the emitted value.

return Observable.fromPromise(getBlob(id))
    .mergeMap((blob) => {

        // Create inner observable based on the blob
        return Observable.fromPromise(blobToBase64(blob))

            // Map the inner result to keep the blob variable
            .map((base64) => {
                return {base64, blob};
            })
    }).subscribe((result) => {
        console.log(result.blob, result.base64);
    });