Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute common code after a Dojo Deferred object is resolved or rejected?

I have a question about dojo/Deferred. I'll start with the question, then go into more detail about what I'm doing:

Is there a way to execute the same lines of code regardless of the outcome of the deferred, sort of like a finally block in a try...catch statement? From what I've read, it doesn't seem like there is, but maybe I'm understanding the documentation wrong and wanted to verify that with the SO community.

Here's what I'm doing:

In Dojo 1.9 (also works in 1.8), I instantiate a dojox.widget.Standby (a loading overlay) for a ContentPane before loading some data. Once the deferred call has completed, I want to hide my overlay as shown below:

standby = new Standby({
    ... // standby props
});
this.addChild(standby);
standby.show();

queryResults = grid.store.query({
    ... // query props
});
queryResults.then(function (results) {
    if (results) {
        ... // do something
    }

    standby.hide();
}, function (error) {
    ... // handle error

   standby.hide();
});

This works fine; however, presumably, I could have some process to be implement after the deferred completes that takes up several lines of code instead of just a single line and I wouldn't want to duplicate those lines of code. An alternative would be to create a private function and just call it with a one-liner in each block, but if there's a better way, I'd rather take that route.

Thanks in advance!

like image 318
David Avatar asked Jun 27 '13 14:06

David


1 Answers

You can use the always method of the Promises API to execute a function regardless of whether the underlying Deferred succeeds or fails.

queryResult
   .then(onSuccess, onFailure)
   .always(function() {
      standby.hide();
   });
like image 55
Lucas Avatar answered Sep 22 '22 18:09

Lucas