Skip to content

Instantly share code, notes, and snippets.

@aseemk
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save aseemk/8b77896ceb12271e6b2a to your computer and use it in GitHub Desktop.

Select an option

Save aseemk/8b77896ceb12271e6b2a to your computer and use it in GitHub Desktop.
CoffeeScript + Streamline patterns for async loading + caching.

Pattern 1: Pre-fetch the result, and cache it.

The result will hopefully already be available when needed, and the async call will be made only once.

fooFuture = fetchFoo !_

# anytime when needed:
foo = fooFuture _   # supports multiple calls!

Pattern 2: Load this lazily, but still cache it.

The async call will again be made only once, but it won't happen until it's needed.

barFuture = null

# anytime when needed:
barFuture or= fetchBar !_
bar = barFuture _     # like pattern 1 above
@aseemk
Copy link
Author

aseemk commented Oct 6, 2014

Futures are already caching their result!

Oh man, I didn't know that! So you can call a future multiple times without error? So slick!

The first pattern could be problematic ...

Great point! I love your suggestion.

Let me update the code above to incorporate both of your fixes.

@bjouhier
Copy link

bjouhier commented Oct 6, 2014

Yep. There are a few undocumented little goodies...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment