Join the DZone community and get the full member experience.Join For Free
You can use this Babel fetch polyfill to bridge the gap. I wonder if that’s good enough to convince our CTO to let me use this.
Then again, why? Oh yeah, that strange Chrome 52 bug doesn’t happen and all I’d have to do was change that one API wrapper function that we use for everything … and thus change our whole codebase … and wreak havoc.
But The Bug doesn’t happen! Let me show you.
Ugh, promises don’t work in the console. That’s a bummer … never did like promises. It’s really just weird syntax sugar for callbacks.
fetch() issues an AJAX request to the server. When it’s done, it triggers the
then part of its promise and gives it a
response object. This object can do many useful things, one of which is to tell you if it was successful. Another is to give you a ReadableStream.
You probably don’t care about readable streams, so there are functions to parse JSON or get raw text. We’re in the brave new world of promises, so those are promises too.
They work like this:
Is supposed to be better than:
But lets get back to the story: You can’t read the fetch response body twice. See that
.text() call? That throws an error saying that oh hey, the body has already been read, so you can’t do it again.
Maybe there’s no good reason you’d want to do that, but what if I do want to?
There’s an even worse caveat, though. Let me show you what happens when your
fetch() call returns a 404.
catch() should give us a chance to catch errors. This keeps our code cleaner because
then() can focus on the happy path.
Somebody decided a 404 error is not a good enough reason to reject the promise. You still have to put a lot of error handling into your happy path.
But The Bug doesn’t happen! I tried. You can repeat the same request in the
then() callback and its
then() callback works just fine.
This debacle makes me wish I was braver when first seeing this behavior 3 months ago. Way back when it was Chrome Canary and I thought surely someone would fix it.
What a strange ride it’s been.
Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.