Saturday, 15 June 2013

javascript - When should I reject a promise? -



javascript - When should I reject a promise? -

i'm writing js code uses promises. example, open form pop-up , homecoming jquery deferred object. works this:

if user clicks ok on form, , validates, deferred resolves object representing form data.

if user clicks cancel, deferred resolves null.

what i'm trying decide should deferred instead reject, instead of resolve? more generally, i'm wondering when should resolve null object, , when should reject?

here's code demonstrating 2 positions:

// resolve null. var promise = form.open() .done(function (result) { if (result) { // result. } else { // log lack of result. } }); // reject. var promise = form.open() .done(function (result) { // result. }) .fail(function () { // log lack of result. });

the semantics of 2 strategies not same. explicitly rejecting deferred meaningful.

for instance, $.when() maintain accumulating results long deferred objects passed succeed, bail out @ first 1 fails.

it means that, if rename 2 promises promise1 , promise2 respectively:

$.when(promise1, promise2).then(function() { // success... }, function() { // failure... });

the code above wait until sec form closed, if first form canceled, before invoking 1 of callbacks passed then(). invoked callback (success or failure) depend on result of sec form.

however, code will not wait first form closed before invoking failure callback if sec form canceled.

javascript jquery jquery-deferred promise

No comments:

Post a Comment