2

I saw following code in the HotTowel project. In the following code, callback method for then returns value return vm.messabeCount = data;

(function () {
    'use strict';
    function dashboard(common, datacontext) {
        vm.messageCount = 0;

        function getMessageCount() {
            return datacontext.getMessageCount().then(function (data) {
                /******* Here ********/
                return vm.messageCount = data;
            });
        }
    }
})();

Am wondering why & to whom it's returning value. Is it some standard practice? Can't the code be just.

return datacontext.getMessageCount().then(function (data) {
    vm.messageCount = data;
});

Or

return datacontext.getMessageCount().then(function (data) {
    vm.messageCount = data;
    return;
});
Pavan Kumar
  • 1,715
  • 1
  • 24
  • 48
  • `return vm.messageCount = data` assigns the data value to vm.messageCount, and also returns that same value.Neither of your two variants have the exact same behavior, which could break the calling code if they actually expect a return value. plus, all functions already have an implicit blank/empty return at the end of the function def. – Marc B Apr 26 '14 at 19:23
  • 1
    Where does `dashboard` actually call the `getMessageCount` function? – Bergi Apr 26 '14 at 19:24
  • @Bergi `getMessageCount` gets called in `dashboard` function. Removed those lines for brevity. – Pavan Kumar Apr 26 '14 at 19:34

1 Answers1

2

getMessageCount is a function returning a promise object. then method of this promise returns another promise again. It makes possible to chain multiple then parts. Each then(function() { ... }) has an ability to modify a data to be passed to the next then invocation. So this construction:

return datacontext.getMessageCount().then(function(data) {
    return vm.messageCount = data;
});

means to modify a data passed to resolve callbacks. Without this return success functions would be resolved with undefined value, while we need it to be resolved with data.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Actually it doesn't really modifiy the data, but is the identity function - and setting global variables to promise results is an antipattern anyway. – Bergi Apr 26 '14 at 19:43