Why doesn't the Reflux.js listenAndPromise helper work?

608 views Asked by At

I'm using qwest to query my endpoint as shown below, the onGetResourceCompleted handler fires as expected but data is undefined. Why?

var Actions = Reflux.createActions({
  'getResource': { asyncResult: true }
});

Actions.getResource.listenAndPromise(function (id) {
  return qwest.get('http://localhost:8000/my-data/'+id, null, { withCredentials: true });
});


var MyStore = Reflux.createStore({

  listenables: Actions,

  init: function () {
    Actions.getResource('');
  },

  onGetResourceCompleted: function (data) {
    console.log('OK', data); // Get's called but data is undefined. Why?
  }

});

I can see the data loads correctly by looking at dev tools as well as calling qwest in isolation by simply doing:

qwest.get('http://localhost:8000/my-data/'+id, null, { withCredentials: true }).then(function(data) {
  console.log('OK', data);
});

Also doing the following works:

ServiceActions.getResource.listen(function (id) {
  ServiceActions.getResource.promise(
    qwest.get('http://localhost:8000/my-data/'+id, null, { withCredentials: true })
  );
});
1

There are 1 answers

0
Brian Vanderbusch On

I've put some comments on the cause of this "confirmed bug" in the original issue you opened at github.com/spoike/refluxjs.

So, though you are using the reflux features the way they are intended, and they're definitely creating a race condition without even returning the race results, I think you're in luck. It turns out the two particular features you're using in this combination with this type of request is a bit redundant when you already have a promise available. I'd recommend you just drop the onGetRequestCompleted handler entirely, and handle completion using the standard promise ways of handling resolved promises, which honestly will give you more flexibility anyways.

For example:

var MyStore = Reflux.createStore({

  listenables: Actions,

  init: function () {
    Actions.getResource('')
      .then()  <-- this eliminates the need for onGetResourceCompleted
      .catch() <-- or this instead/in addition
      .finally() <-- or this instead/in additon
  },

  // no more onGetResourceCompleted

});