3

I have a section in my code that looks like this

var locationDefer = $.Deferred();

if (saSel.Company === -1) {
    database.getAllLocations().then(function (result) {
        var locations = JSON.parse(result.d);
        locationDefer.resolve(locations);
    });
} else {
    database.getLocationsForCompany(saSel.Company).then(function (result) {
        var locations = JSON.parse(result.d);                   
        locationDefer.resolve(locations);
    });
}

However, since it is basically the same thing twice, just with a different ajax call - is there any way to either have the anonymous function part

function (result) {
    var locations = JSON.parse(result.d);
    locationDefer.resolve(locations);
})

declared as a real function and then just called in the .then() clause, or can I somehow provide the to-be-called-function of the database object?

For the latter, I had something in my mind that could look like this, but I have no clue how to do the last line.

if(saSel.Company === -1) {
    fun = 'getAllLocations';
    arg = null;
} else {
    fun = 'getLocationsForCompany';
    arg = saSel.Company;
}

// database.fun(arg).then(function (result) {...});
Decay42
  • 802
  • 1
  • 9
  • 20
  • Avoid the [deferred antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jul 10 '17 at 09:37
  • "*is there any way to either have the anonymous function part declared as a real function and then just called in the .then() clause*" - of course there is! No method cares about the syntax you use as long as you pass a function as the argument. Have you tried it? – Bergi Jul 10 '17 at 09:38
  • Don't use `fun` and `arg`. But you can trivially store the promise that either `database.getAllLocations()` or `database.getLocationsForCompany(saSel.Company)` return in a variable, and then call `.then()` on that variable. – Bergi Jul 10 '17 at 09:40

1 Answers1

3

You can define a function and pass its reference as success callback handler

//Define the function handler
function resultHandler(result) {
    var locations = JSON.parse(result.d);
    locationDefer.resolve(locations);
}

if (saSel.Company === -1) {
    fun = 'getAllLocations';
    arg = null;
} else {
    fun = 'getLocationsForCompany';
    arg = saSel.Company;
}

//Invoke the method using Bracket notation
//And, pass the success handler as reference
database[fun](arg).then(resultHandler);

Additionally, as getLocationsForCompany() and getAllLocations() returns a promise, you shouldn't use $.Deferred() directly return Promise

return database[fun](arg);
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Wow, calling the function by name with database[name](arg) didn't come to mind. Thank you very much! – Decay42 Jul 10 '17 at 09:26