Skip to content

Instantly share code, notes, and snippets.

@aseemk aseemk/async-loading.md
Last active Aug 29, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Oct 6, 2014

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

whenNeeded = fetchBar !_
@bjouhier

This comment has been minimized.

Copy link

commented Oct 6, 2014

Futures are already caching their result!

@bjouhier

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link
Owner Author

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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.