Get PromiseState When Using Fetch

Viewed 61

I have the following function that uses fetch:

function requests(url) {
  return fetch(url)
    .catch(function (error) {
      return null;
    })
    .then(function (response) {
      if (response == null) {
        return null;
      } else if (!response.ok) {
        if (response.status == 422) {
          // HIT No longer exists
          return null;
        } else if (response == 429) {
          //too many requests
          return null;
        }
        console.log("caught error: " + response.status);
        return null;
      }
      js = response.json();
      console.log(js);
      return js;
    });
}

My problem is that occasionally the fetch is 'rejected'. None of the code catches that error until I try to read 'response.json'. I cannot find how to access the 'PromiseState' in 'js'. When I log "js" I get this:

Promise
  [[Prototype]]: Promise
  [[PromiseState]]: "rejected"
  [[PromiseResult]]: SyntaxError:      Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Can someone help me with this?

1 Answers

With await js = response.json(); your code assigns a promise to js, while it would be more useful to do js = await response.json(); to get the promised value.

Moreover, js is apparently declared with an implicit global scope. It would be good to use let, const or var to make it local.

While for the first promise (fetch) your code has error handling, there is none for this second promise .json().

Finally, response == 429 is never going to be true. I suppose you intended to test the status property.

Here is how it would look without .then/.catch, but with a try/catch block:

async function requests(url) {µ
    try {
        const response = await fetch(url);
        if (!response?.ok) {
            if (response && ![422, 429].includes(response.status)) {
                console.log("caught error: " + response.status);
            }
            return null;
        }
        const js = await response.json();
        console.log(js);
        return js;
    } catch(error) {
        return null;
    }
}
Related