0

I'm having trouble understanding Promise.resolve.

I'm writing a very simple wrapper for fetch to avoid having to write a then just to access the JSON. I found a code snippet online that looked a bit like this:

  function get(url) {
    return fetch("/api/" + url, {
      method: "GET",
      credentials: 'include'
    }).then(response => {
      if (response.ok) {
        return response.json().then(json => {
          return Promise.resolve({ data: json, response: response });
        }).catch(err => {
          return Promise.resolve({ response: response });
        });
      } else {
        return response.json().catch(err => {
          throw new Error(response.statusText);
        }).then(json => {
          throw new Error(json.error.message);
        });
      }
    });
  }

However, it doesn't seem like you need the Promise.resolve function calls. I tried removing them and just writing return { data: json, response: response }; instead and it still works.

Are the resolve calls doing anything? Are they necessary?

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • 3
    No, they are not necessary – blex Feb 29 '20 at 00:05
  • So it's just a no-op? Why were they included? User error? – Ryan Peschel Feb 29 '20 at 00:06
  • It's not necessary to use Promise.resolve or Promise.reject inside of a handler like this; these methods are intended to provide you a way to _start_ a promise chain, not to continue one. – Hamms Feb 29 '20 at 00:06
  • No, they are not necessary. If you return something from a `then` you can still chain it with another `then` since it's a `Promise` - no need to explicitly say `return Promise.resolve()` – goto Feb 29 '20 at 00:06
  • Alright, thanks for the quick response! – Ryan Peschel Feb 29 '20 at 00:06
  • @RyanPeschel no idea why are they're there - perhaps the original author had it confused, but there's no need for doing this. – goto Feb 29 '20 at 00:07
  • do your own test... replace those `return Promise.resolve({ ... })` with `return { ... }` and instead of `throw new Error(...` just `return new Error(...` - this only works because with `return fetch` you are telling that you are retuning a promise... all you need now is to return the data (or the error). – balexandre Feb 29 '20 at 00:19

1 Answers1

0

Are the resolve calls doing anything?

Yes, they wrap the value into a Promise that resolves with that value. As you return them from within a .then, the Promise returned by the .then method will resolve to the same value the returned Promise resolves to.

Are they necessary?

No.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151