0

If I deal with an arbitrary array which values have to be mapped to promises and it is crucial to wait for previous call completion before the next one performed, I usually follow this pattern:

const later = ms => new Promise(resolve => setTimeout(_ => resolve(console.log(ms)), ms)); console.log('chain start') let chain = Promise.resolve(); [1, 2, 3, ...].forEach(val => chain = chain.then(later.bind(null, val * 100))) chain.then(_ => console.log('chain end')) 

The important parts here are that 1 - we don't know how many items array could carry and 2 - we can't use Promise.all (consecutive calls or queue required).

The question is: What is the best RxJS way of doing so? So, observables instead of promises.

(I'm aware of .toPromise)

1 Answer 1

3

assume all your array contains [urls]

from([url1,url2,url3...]).pipe(concatMap(url=>defer(()=>fetch(url)))) .subscribe(results=console.log(results)) 
Sign up to request clarification or add additional context in comments.

3 Comments

this assumes fetch returns a cold observable. May be better to do concatMap(url => defer(() => fetch(url))) to be safe.
Also you cannot call pipe on an array. I think you are missing from([url1, url2, ...]).pipe(...
@Brandon I don't think defer is needed here even with hot Observables as concatMap will only call the given function if the previous Observable completed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.