fac-13 / jeth

Find jobs near you :computer:
https://jeth.herokuapp.com/
1 stars 2 forks source link

More general fetch function #37

Open eliasmalik opened 6 years ago

eliasmalik commented 6 years ago

https://github.com/fac-13/jeth/blob/55aa475205ea69a649432a9c9cfd0b7e1854d083/public/dom.js#L3

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

https://github.com/fac-13/jeth/blob/55aa475205ea69a649432a9c9cfd0b7e1854d083/public/dom.js#L9-L23

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? */)
    }
    }
  2. Use the error-first callback pattern:

    const fetch = (url, callback) => {
    // ...
    if (/* successful request */) {
    callback(null, /* data */)
    } else {
    callback(/* error message? */)
    }
    }
helenzhou6 commented 6 years ago

Can we try doing the error-first callback pattern to get more practice at doing that? 😊