1

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" 
4

1 回答 1

1

我认为,您应该使用流对象的错误回调,而不是寻找状态文本。 例如,合并请求并处理任何错误(JS,对不起,我不熟悉 Coffee Script):

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

或者,您可以使用该mapError函数将错误事件合并到可观察流中:

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

小提琴

编辑

您可以从fromPromise 源中看到对“数据”对象的任何引用都被吞没了。你fromPromise给它的承诺就是将 observable 的处理程序绑定到promise.then“已解决”和“已拒绝”回调:

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()];
    });
  };

换句话说,您可以访问状态文本的唯一方法是保存对 Promise 对象的引用。但你不需要这样做——你只需要处理培根的observable.onError.

于 2013-10-14T00:11:57.077 回答