I looked at this question about caching and this one about conditional promises but to be honest, I'm still a bit confused, as I've never used promises before.
I'm using when.js v2.5.1 and jQuery v2.0.3. I'm trying to convert the following code into a promise (it's so much clearer in coffeescript so I'll stick with that, but feel free to respond with javascript)
class Loader
@files: {}
@load: (path) ->
@files[path] ?= $.ajax(url: path).responseText
to be called like this:
mytext = Loader.load "/path/to/greatness"
So, I know I want to return a promise. I know jQuery's xhr is a deferrable and implements the Promise API Something, so could I do something like this?
class Loader
@files: {}
@load: (path) ->
if @files[path]
deferred = When.defer()
deferred.resolve @files[path]
deferred.promise
else
$.ajax(url: path).done (data)=>
@files[path] = xhr.responseText
because whatever gets returned can have then
called on it…?
Any help is much appreciated.