4 ms·
XMLHttpRequest has a synchronous version, where as fetch does not. For instance, this means you can do an XMLHttpRequest in your app's router, and decouple you
by ok123456 5y ago
XMLHttpRequest has a synchronous version, where as fetch does not.
For instance, this means you can do an XMLHttpRequest in your app's router, and decouple your presentation from dealing with endpoints. Fetch can't do this.
- zelphirkalt 5y agoYou could just await the async thing though, to make it synchronous.
- TedDoesntTalk 5y agoYou can use a async/await with fetch to force it to be synchronous.
- kevingadd 5y agoasync/await is not synchronous, it's promises under the hood
- TedDoesntTalk 5y agoBut from a programming standpoint, you are assured that the next induction Edie’s not execute until the response is received.
- kevingadd 5y agoFunctionally this is still very different from sync xhr. Changing from sync xhr to await+fetch will introduce new bugs into your application unless it was written carefully, because now code can run and interactions can happen during the fetch that would have been blocked by the sync xhr occupying the event loop. Promises are also specced so that their handlers don't run until the event loop completes a turn, which means that no matter what there is now an opportunity for queued callbacks to run before you actually process the response to your request, even if it hit in-memory cache.
- Jasper_ 5y agoI would really love a synchronous spinMicrotasks() API, but for obvious reasons it's likely never happening.
- simlevesque 5y agoYour router could wait for async function and you could use await in your router's function, accomplishing the exact same thing but without blocking the main thread.
- gwbas1c 5y agoThat's a very bad point to block your UI thread. Your router should not block, and the UI on your next page should show a spinner or other loading indicator while it runs a fetch (or XmlHTTPRequest)
- ok123456 5y agoIt's better for testing.
- RussianCow 5y agoYou mean unit testing? How so? I have never seen unit tests make real HTTP requests; it's much better to mock them. And changing from async to sync code for unit tests sounds like a bad idea, since you're not testing your code the way it actually works in production.
- gwbas1c 5y agoThat's an unjustified excuse. The one thing that is consistent with UI programming among all platforms is that you never block the UI thread. You should be able to mock fetch/xmlhttprequest at any point, not just in your router. You should be able to mock those calls without needing to block the UI thread at runtime.
- ok123456 5y agoNo it's not. If you have to mock things like that it's a sign of poorly designed, stateful objects.