Search code examples
javascriptqpolling

how to keep resolving Q promises when polling


I'm trying to poll an endpoint and use Q to resolve the request. However I understand you can't really do this with Q, as once the promise is resolved it's done.

Is there a way I can approach using Q along with my polling?

My setup is something like:

class Poller {
  poll() {
    const deferred = Q.defer();

    const promise = $.ajax({ 
      //stuff 
    });

    promise.done((resp) => {
      // this resolves just once, how can I keep resolving
      // on future xhr calls?
      deferred.resolve(resp);
    });

    promise.always(() => {
      setTimeout(() => {
        this.poll.call(this);
      }, 5000)
    })

    return deferred.promise;
  }

}

const poller = new Poller();

poller.poll().then((resp) => {
  // keep trigging updates from polling
})

Solution

  • The whole point of a promise is that it can only be resolved once. The structure you are looking for is an event.