Hacker News new | ask | show | jobs
by shrew 1747 days ago
I'm genuinely curious to know what you find severely lacking in fetch compared to $.ajax.

- handling cookies

    fetch('https://example.com', { credentials: 'include' })
- HTTP status codes

    fetch('https://example.com').then(response => {
        if (response.ok) {
            // Response is 200-299
        }
        if (response.status === 404) {
            // Status code specific handling
        }
    });
- CORS

    fetch('https://example.com', { mode: 'no-cors' });
- JSON handling

    fetch('https://example.com').then(response => response.json()).then(json => {
        // Do something with a parsed JSON object
    });
I've used all of the above patterns regularly for several years now and never found any of them particularly cumbersome and certainly not lacking feature wise. If async/await syntax is available to you, it's even more succinct than the Promise style above.

With that said, I've not used $.ajax in anger for a good long while so I may be missing out, particularly as I note there have been API changes in newer versions of jQuery. Are there some specific use cases that you've found fetch to be particularly inept in dealing with?

1 comments

These are great snippets! Although, your last snipped definitely shows the readability problem (even though you do a good job with it!)

Because each intermediate step is async as well, fetch can definitely turn into "callback hell" (really, promise hell) that the old callback style of JS used to be well-known for (and was resolved in large part by jQ-style chaining in the form of promises).

You might have a look at this link, especially the "Differences with jQuery":

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

"The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

"fetch() won’t send cross-origin cookies unless you set the credentials init option (to include)."

With regards to CORS, you have very limited options as well: no-cors, cors, same-origin. I've definitely had issues with CORS requests that didn't apply to XHR (and jQuery's AJAX by extension.)

"Note that mode: "no-cors" only allows a limited set of headers in the request:

"Accept Accept-Language Content-Language Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain"

For example:

"Note: Access-Control-Allow-Origin is prohibited from using a wildcard for requests with credentials: 'include'. In such cases, the exact origin must be provided; even if you are using a CORS unblocker extension, the requests will still fail."

The latter quotes from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/U...