0

Background

I started working at a company that doesn't have many patterns and I see the return of fetch calls in two ways. One returning just the fetch call and another returning a fetch call wrapped by Promise using resolve and reject, and this made me get confused.

Question

Is doing this

const returnFetchWrappedByPromise = () => {
    return new Promise((resolve, reject) => {
        return fetch("url")
            .then(resolve(true))
            .catch(reject(false))
    })
}

The same as this

const returnFetch = () => {
    return fetch("url")
        .then(() => true)
        .catch(() => false)
}

?

If not, what is the difference?

If yes, which one should I use?

Observation: I used true and false just to make an example, but in reality, is some result and some error.

Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • 2
    Those should be callbacks: `then(() => true, () => false)` – Bergi Apr 29 '19 at 21:57
  • 1
    Not many patterns, but some antipatterns: [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! And of course: avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Apr 29 '19 at 21:57
  • 1
    Should be easy to test. Run both and see (bearing in mind @Bergi's comments). – Heretic Monkey Apr 29 '19 at 21:59
  • @Bergi thanks for the related posts, this gave me such better understanding of how promises works. – Vencovsky Apr 29 '19 at 22:08

2 Answers2

-1

fetch inherently returns a promise, so wrapping it in a new Promise doesn't add any functionality. The use of async also does not add anything in this case and actually presents a case of the Promise constructor anti-pattern.

The second function syntax is the preferred way.

Yannick K
  • 4,887
  • 3
  • 11
  • 21
-1

The new Promise object within the returnFetchWrappedByPromise function is not needed. fetch already returns a Promise object (Screenshot below). You should use the returnFetch function. Hope that helps.

Console Screenshot

Ervi B
  • 770
  • 7
  • 16