Skip to content

Instantly share code, notes, and snippets.

@aseemk
Last active August 29, 2015 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aseemk/8b77896ceb12271e6b2a to your computer and use it in GitHub Desktop.
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
@bjouhier
Copy link

bjouhier commented Oct 6, 2014

Cool but the bar variable does not buy you much. What about the following?

whenNeeded = fetchBar !_

@bjouhier
Copy link

bjouhier commented Oct 6, 2014

Futures are already caching their result!

@bjouhier
Copy link

bjouhier commented Oct 6, 2014

The first pattern could be problematic if you have several tasks competing for the resource the first time it is accessed. The problem is that several fetchFoo calls will be launched in parallel (foo or= fetchFoo _ is not atomic). I typically use a funnel to avoid that but your second pattern gives an interesting alternative to solve it:

fooFuture = null

whenNeeded = (_) ->
    fooFuture or= fetchFoo !_
    fooFuture _

Note: the fooFuture or= fetchFoo !_ instruction is atomic. It does not yield so there is no risk of launching fetchFoo more than once.

@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