Skip to content
David Chase edited this page Nov 15, 2016 · 3 revisions

Sometimes when dealing with promises you only want the results of those resolved and don't care about rejections.

This simple example shows that we want only the successful promises in order to log 'hello world!'

import {fromPromise, from, empty} from 'most'

const ignoreErrors = promise => fromPromise(promise).recoverWith(empty)

from([
  Promise.resolve('hello'),
  Promise.reject('boom'), 
  Promise.resolve('world!'),
  Promise.reject('bang!!')
])
.chain(ignoreErrors)
.observe(console.log) 
// logs
// => hello 
// => world

Another case (closer to real-world) maybe that you have an array of urls and some of those urls may timeout or might not exist altogether:

const urls = [
 'https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1',
 'https://deckofcardsapi.com/api/deck/new/shuffle/30' // will fail
]

from(urls)
.map(fetch)
.chain(ignoreErrors)
.chain(resp => fromPromise(resp.json()))
.observe(console.log) // logs the object from the success url

Demo here

The main function here is ignoreErrors which simply takes a promise argument says if any time a promise fails or rejects

take those errors and recoverWith or rather replace those errors with an empty stream (a stream that has ended already and contains no events).