Skip to content

Commit 67d8407

Browse files
committed
promises - guarantee options.success/error are called first
1 parent cf54088 commit 67d8407

File tree

2 files changed

+29
-7
lines changed

2 files changed

+29
-7
lines changed

backbone.js

+23-5
Original file line numberDiff line numberDiff line change
@@ -1248,16 +1248,26 @@
12481248
// Make the request, allowing the user to override any Ajax options.
12491249
var xhr = options.xhr = ajax(_.extend(params, options));
12501250

1251+
model.trigger('request', model, xhr, options);
1252+
1253+
var success = options.success;
12511254
var error = options.error;
1252-
xhr.then(options.success, function(xhr, textStatus, errorThrown) {
1255+
var that = this; // actually needed?
1256+
1257+
// pipe the results through "then", to gurarantee that
1258+
// options.success and options.error are called before
1259+
// the returned promise resolves. This gives the
1260+
// collections/models a chance to update first.
1261+
return xhr.then(function() {
1262+
success.apply(that, arguments);
1263+
return thenArgs(arguments);
1264+
}, function(xhr, textStatus, errorThrown) {
12531265
// Pass along `textStatus` and `errorThrown` from jQuery.
12541266
options.textStatus = textStatus;
12551267
options.errorThrown = errorThrown;
1256-
if (error) error.apply(this, arguments);
1268+
if (error) error.apply(that, arguments);
1269+
return failArgs(arguments);
12571270
});
1258-
1259-
model.trigger('request', model, xhr, options);
1260-
return xhr;
12611271
};
12621272

12631273
var noXhrPatch =
@@ -1701,6 +1711,14 @@
17011711
};
17021712
};
17031713

1714+
var thenArgs = function() {
1715+
return $.Deferred().resolve(arguments);
1716+
};
1717+
1718+
var failArgs = function() {
1719+
return $.Deferred().reject(arguments);
1720+
};
1721+
17041722
return Backbone;
17051723

17061724
}));

test/sync.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,12 @@
215215
strictEqual(options.textStatus, 'textStatus');
216216
strictEqual(options.errorThrown, 'errorThrown');
217217
});
218-
var rawDeferred = model.fetch();
219-
rawDeferred.reject(rawDeferred, 'textStatus', 'errorThrown');
218+
model.fetch({
219+
ajax: function() {
220+
var dfd = $.Deferred();
221+
return dfd.reject(dfd.promise(), 'textStatus', 'errorThrown');
222+
}
223+
});
220224
});
221225

222226
})();

0 commit comments

Comments
 (0)