Domanda

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.

È stato utile?

Soluzione

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]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top