0

Having recently "graduated" to using Promises, I worked up this pattern that absolutely does work, but I'm wondering if it is "technically" correct, or "best practices"? GetAsync() is a function that makes a fetch() call to an API endpoint and receives back a JSON response.

new Promise((resolve, reject) => {
    GetAsync("../api/CurrentUserAccount", resolve, reject, "json")
})
    .then((result) => {
        // code that does stuff with the user account json
    });

Again, this works just fine, but doing it this way, I am never doing anything with either resolve or reject. That makes me think "I'm doing this wrong." Is there a better, or more proper way to do this?

KWallace
  • 1,570
  • 1
  • 15
  • 25
  • 4
    Please show the contents of the `GetAsync` function. – Heretic Monkey Sep 03 '22 at 22:09
  • 3
    That would only depend on whether the `GetAsync` really expects the res/rej pair of the promise function. Which would be rather uncommon, in my opinion. – Wiktor Zychla Sep 03 '22 at 22:11
  • 3
    *"...makes an xmlHttpRequest()"* any reason that you're not using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch)? – Thomas Sep 03 '22 at 22:18
  • For best practices, see [this answer](https://stackoverflow.com/a/25756564/1048572). In particular, you should be calling the `new Promise` *inside* of `GetAsync` and make it `return` the promise. – Bergi Sep 03 '22 at 22:41
  • @Thomas, thanks for pointing that out. I am actually using fetch(). Sorry. Updated question. – KWallace Sep 03 '22 at 23:05
  • @Bergi, thanks. That's kinda what I figured I was doing wrong. – KWallace Sep 03 '22 at 23:07
  • 4
    @KWallace If you're actually using `fetch` inside of `GetAsync`, then this definitely goes against best practices, in particular it's the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it). – Bergi Sep 03 '22 at 23:07
  • @Bergi. Got it. Will adjust accordingly. – KWallace Sep 03 '22 at 23:09

0 Answers0