3 ms·
This sounds like a good use case for Promise.all() and fetch: const first = fetch(endpoint1); const rest = Promise.all([ fetch(e2), fetch(e3), fetch(e4
by 18nleung 9y ago
This sounds like a good use case for Promise.all() and fetch:
const first = fetch(endpoint1);
const rest = Promise.all([
fetch(e2), fetch(e3), fetch(e4),
]);
// cancel here
const json1 = await first.json();
const json234 = await rest.json();
While native promises can't cancel on their own, with a library like Bluebird you can get that functionality.
- captainmuon 9y agoYes! Promises and window.fetch are nice, that's what I based my code on. I am thinking about switching to axios (or Bluebird) to get cancellation, though. But this is just the low-level code. Instead of (pseudocode): window.fetch('/the/api/url') .then(res => res.json()) .then(json => this.setState({thing: json['thing']})); I do (something like): fetchFromServerOrCache('param', 123) .then(obj => this.setState({data: data})); The minor difference is that I do some processing (ok, you can do that somewhere is), but the main thing is the caching. The user can drag a slider bar and select different 'frames', and I don't want to transmit everything again if the frame was already selected. For various reasons I can't rely solely on the browser cache. One reason is that I prefetch all frames the server already computed at the beginning. So I want to check if the frame is available from the initial batch, or a subsequent fetch, and if not, fetch it in place. I wrap it into a promise so the calling code does not need to know about the caching. I then pass the state to a child component which is as pure as possible.