nathancahill
nathancahill

Reputation: 10850

Promise pattern falling back multiple fetches

I'm using fetch promises to fall back through 3 API calls until one succeeds. I'm not sure what the best pattern is for that. I'd like to use something like this, where promise rejection is handled by the next catch and fetches the next URL.

The issue is that successfully resolved data is picked up by .then(res => res.json())

fetch(url1)
    .then(res => res.json())
    .then(data => {
        if (data.status !== 'OK') {
            return Promise.reject()
        }

        return Promise.resolve(data)
    })
    .then(null, () => {
        return fetch(url2)
    })
    .then(res => res.json())
    .then(data => {
        if (!data.success) {
            return Promise.reject()
        }

        return Promise.resolve(data)
    })
    .then(null, () => {
        return fetch(url3)
    })
    .then(res => res.json())
    .then(data => {
        if (data.error) {
            return Promise.reject()
        }

        return Promise.resolve(data)
    })

The success checks are different for each function, so I can't easily use a loop that breaks on success.

Upvotes: 0

Views: 66

Answers (2)

Fabricator
Fabricator

Reputation: 12782

Just group the optional API call and processing in the catch function:

fetch(url1)
  .then(res => res.json())
  .then(data => {
    if (data.status !== 'OK') {
      return Promise.reject()
    }

    return Promise.resolve(data)
  }).catch(function() {
    return fetch(url2)
      .then(res => res.json())
      .then(data => {
        if (!data.success) {
          return Promise.reject()
        }

        return Promise.resolve(data)
      });
  }).catch(function() {
    return fetch(url3)
      .then(res => res.json())
      .then(data => {
        if (data.error) {
          return Promise.reject()
        }

        return Promise.resolve(data)
      })
  });

Upvotes: 1

Mario Santini
Mario Santini

Reputation: 3003

You could use Promise.all or Promise.race, and wrap the checks on functions.

Upvotes: 0

Related Questions