Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an array of Promises to a stream (of Observables?)

Tags:

promise

rxjs

Let's say I have an array of promises, itemsPromises. Some of them will fail, half of them will probably succeed.

If I try to get the responses like so:

const itemsPromises = raw.map(item =>
            axios({
                method:'get',
                url:`https://www.omdbapi.com/?apikey=${apikey}&i=${item.imdbID}`
            })
        )

const itemsResponses = await Promise.all(itemsPromises)

...I will need to wait a LONG time until the failing promises time out, eventually. I may get 5-6 successful reponses but won't have access to them untill ALL of the promises are resolved or rejected.

Can I convert this array of Promises to some iterable form of Observables, so that every time I get a successful response I can pass it on to my application and use it?

like image 476
chachathok Avatar asked Sep 17 '25 09:09

chachathok


1 Answers

Merge operator lets you execute each http call simultaneously

Rx.Observable.merge(null,
raw.map(item =>
    Rx.Observable.fromPromise(axios({
        method: 'get',
        url: `https://www.omdbapi.com/?apikey=b54e8554&i=${item.imdbID}`
    })).catch(err=>Rx.Observable.of({err,item}))
)).subscribe()
like image 109
Fan Cheung Avatar answered Sep 21 '25 04:09

Fan Cheung