Frage

jQuery's Ajax handler returns an array of arguments when its promise resolves, and the initial tuple is ([data], "status"). I've found that when I use Bacon.fromPromise, all I get back is the data. How would I get the status of the transaction, and how would I handle any actual failures from jQuery?

What I'm trying to do is download two bundles of data, of the same schema, from two different URLs and concatenate them. I think I've got the concatenation figured out, but the error handling is driving me nuts. Here's what I'm trying:

requestData = Bacon.fromPromise $.get @users_stories
requestRefs = Bacon.fromPromise $.get @reference_stories

success = (d, s) -> s == "success"
fetchFailure = requestData.map(success).not()
    .merge(requestRefs.map(success).not())
fetchFailure.onValue => alert "Failed to download" 
War es hilfreich?

Lösung

I think that, instead of looking for the status text, you should be using the error callback of the stream objects. For example, to merge the requests and handle any errors (JS, sorry, I'm not fluent with Coffee Script):

requestData.merge(requestRefs).onError(function(e) {
    alert("Failed to download: " + e.responseText);
});

Alternatively, you can use the mapError function to merge the error events into the observable stream:

requestData.merge(requestRefs).mapError(function(e) {
    return e.statusText;
}).onValue(function(next) {
    if (next.feed) {
        // handle feed
    } else {
        alert("Error: " + next);
    }
});

Fiddle

Edit

You can see from the fromPromise source that any reference to the "data" object is swallowed up. All fromPromise does with the promise you give it is to bind the observable's handler to the promise.then's "resolved" and "rejected" callbacks:

Bacon.fromPromise = function(promise, abort) {
    return Bacon.fromBinder(function(handler) {
      promise.then(handler, function(e) {
        return handler(new Error(e));
      });
      return function() {
        if (abort) {
          return typeof promise.abort === "function" ? promise.abort() : void 0;
        }
      };
    }, function(value) {
      return [value, end()];
    });
  };

In other words, the only way you can get access to the status text would be to save a reference to the promise objects. But you don't need to do that -- all you need is to handle Bacon's observable.onError.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top