2

I have a function that returns a function (a async .get call). Here I am returning a empty object in my catch statement:

export function makeHttpStatsProvider(fisClientRoot, httpClient, selectedDate = null) {
    return async function(polygon, layerName) {
        const response = await httpClient.get(
         ///request logic
        }}).catch((e) => {
          return {}
        }).then((response) => {
          return {[layerName]: response.data[layerName][0].basicStats}
        })
    }
}

Then I have a function that takes this promise and makes an array of promises:

export async function harvestMap(statsProvider, polygons, numBuckets = 5) {

    const arrayOfPromises = polygons.map(async (polygon) => {
      Object.assign({}, polygon, await statsProvider(polygon, 'EVI'))
    })

    return Promise.all(arrayOfPromises)
      .catch((err) => {
        console.log('a promise failed to resolve', err)
        return arrayOfPromises
      })
      .then((arrayOfPromises) => {
        return arrayOfPromises.sort((a, b) => a.EVI.mean - b.EVI.mean).map((polygon, index) => Object.assign({}, polygon, {
          rank: Math.floor(index * numBuckets / polygons.length)
        }))
      })

}

Here the .catch statement console.log an error. But despite this, the arrayOfPromises in the .then() statement still includes rejected promises.

What I would like to achieve is to return a custom object when the network request fails, and pass it to the Object.assign function later on. Is this even possible or do I need to approach the problem in a different way?

Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163
  • If one of the Promises passed to `Promise.all` fails then _closest_ `.catch` is executed, and the value returned from that callback is passed to then next `.then` callback in the chain. So on failure the `arrayOfPromises` in the `.then` will be `arrayOfPromises` that you pass to `Promise.all`. – t.niese Jun 16 '17 at 12:06
  • `.catch((e) => { return {}` - means there is no rejection anymore – Jaromanda X Jun 16 '17 at 12:12
  • You'll want to use `.then(…).catch(…)` [or even `.then(…, …)`](https://stackoverflow.com/q/24662289/1048572) instead of `.catch(…).then(…)` – Bergi Jun 16 '17 at 13:10

0 Answers0