1

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.

Community
  • 1
  • 1
ian
  • 12,003
  • 9
  • 51
  • 107

1 Answers1

1

You are firing off multiple requests for the same file because the if test gives false until the request completes. You should immediately assign it so only one request for a file is ever made

The resolution value of successfull ajax should a meaningful reflection of the responseText anyway so you can just do this:

class Loader
  @files: {}
  @load: (path) ->
    if not @files[path]
      @files[path] = $.ajax(url: path)
    @files[path]
Esailija
  • 138,174
  • 23
  • 272
  • 326