0

Say I have a bunch of promises in my application that are just like this:

const fetchUser = id => new Promise((resolve, reject) => {
  const request = new XMLHttpRequest()
  
  request.open('GET', 'blabla')

  request.onload = () => {
    if (request.status >= 400 && request.status <= 500) {
      reject(Error(JSON.parse(request.responseText)))
    } else {
      resolve(JSON.parse(request.responseText))
    }
  }

  request.onerror = () => reject(Error('There was a problem when fetching a user'))
  
  request.send()
})

That's bad practice since I am just copy and pasting the request.onload and request.onerror portion for every Promise I make. So I could do something like this:

request.onload = handleLoadedRequest
request.onerror = handleBadRequest

and create these two new functions. However, how would I resolve and reject inside these functions?

const handleBadRequest = () => reject(Error('Oops!'))
kibe
  • 90
  • 1
  • 8
  • 26

2 Answers2

2

You can use Promise.resolve() and Promise.reject() which will resolve and reject the Promise immediately. It's also good practice when rejecting the Promise to wrap it in an Error object (if it's not already). That way, among other things, you will have the stack trace. See the Mozilla docs for an example: https://developer.mozilla.org/en-US/docs/web/javascript/reference/global_objects/promise/reject

I typically wrap my ajax requests and XHR requests in a function which returns a Promise; this is referred to as Promisify. See this post for an example of Promisifying your XHR: https://stackoverflow.com/a/30008115/1617161

You don't really need to pass the resolve and reject functions along to other functions. Your other functions will be Promises which resolve or reject their own Promise; that allows for chaining the Promise. Then, you call .then() and .catch() on the Promises in the call chain to either continue or catch the error.

iCode
  • 1,254
  • 1
  • 13
  • 16
1

Simply pass resolve and reject to the handleLoadedRequest and handleBadRequest functions.

const handleLoadedRequest = (resolve, reject) => () => {
...
}

const handleBadRequest = (resolve, reject) => () => {
...
}

const fetchUser = id => new Promise((resolve, reject) => {
  const request = new XMLHttpRequest()
  
  request.open('GET', 'blabla')

  request.onload = handleLoadedRequest(resolve, reject);

  request.onerror = handleBadRequest(resolve, reject);
  
  request.send()
})