DEV Community

loading...

Discussion on: Resolve promises in sequence with RXJS (ConcatMap)

Collapse
johncarroll profile image
John Carroll • Edited

Your example can be simplified to:

from([1, 2, 3]).pipe(
  concatMap(id => 
    fetch(`url-to-api/${id}`)
      .then(res => res.json())
  ),
).subscribe()
Enter fullscreen mode Exit fullscreen mode

Operators expecting an ObservableInput<T>, such as concatMap, automatically coerce promises to observables. And observables built from promises automatically complete when the promise resolves.

From the rxjs source code:

export type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T> | Iterable<T>;
Enter fullscreen mode Exit fullscreen mode

If you wanted to modify the promise's response, you can do that with an async function. For example:

from([1, 2, 3]).pipe(
  concatMap(async id => {
    const res = await fetch(`url-to-api/${id}`);
    const json = await res.json();
    // do stuff
    return json;
  }),
).subscribe()
Enter fullscreen mode Exit fullscreen mode