Skip to content

More general fetch function #37

@eliasmalik

Description

@eliasmalik

const fetch = function (url, callback) {

This is fine, but you've hardcoded specific error handling actions inside this function:

jeth/public/dom.js

Lines 9 to 23 in 55aa475

} else if (xhr.readyState === 4 && xhr.status === 500) {
const main = document.querySelector('.main');
const alertHead = document.createElement('h1');
const alertText = document.createTextNode('Oopsy doodle, there has been a problem');
const bod = document.querySelector('.body');
while (alert.firstChild) {
alert.removeChild(alert.firstChild);
}
alertHead.appendChild(alertText);
alert.appendChild(alertHead);
} else {
console.log('XHR error', xhr.readyState);
}

For a larger app, it makes sense to make this function more general (and therefore more versatile), by allowing some arbitrary function to be executed in the case of an error (just like you're doing in the case of a successful response). There's two ways you can do this:

  1. Accept a second callback argument in fetch.
const fetch = (url, successCallback, failureCallback) => {
  // ...
  if (/* successful request */) {
    successCallback(/* data */)
  } else {
    failureCallback(/* error message? */)
  }
}
  1. Use the error-first callback pattern:
const fetch = (url, callback) => {
  // ...
  if (/* successful request */) {
    callback(null, /* data */)
  } else {
    callback(/* error message? */)
  }
}

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions