Skip to content

Instantly share code, notes, and snippets.

@jamesplease
Last active April 13, 2018 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesplease/6d502afc4b2d7240072a4e38d8dcbb55 to your computer and use it in GitHub Desktop.
Save jamesplease/6d502afc4b2d7240072a4e38d8dcbb55 to your computer and use it in GitHub Desktop.

Clone instead of reading the response.

fetch(input, init)
  .then(res => {
    // Store the response back from the server. This response will be
    // kept in an unused state. Anytime a user requests it, it will be
    // cloned from.
    cache[key] = {
      res,
      // whether or not the data is still being returned from the server or not
      isStreaming: true
    };
    
    // Track the stream status with a clone. This will update
    // the `isStreaming` property once it is done
    trackStream(res.clone(), key);
    
    // Return the cloned response to the user
    return res.clone();
  });

Caveats

  • Cannot push an update to the user once the stream is done
  • Would probably need a terrible API: myLib.isStreaming(), or something

Or...

fetch(url, {
  observe(observer) { 
    observer.onresponseprogress = e => console.log(e);
    observer.onrequestprogress = e => console.log(e);
    observer.onstatechange = n => console.log(observer.state)
  }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment