Anonymous function argument

I have a section in my code that looks like

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 another ajax call - is there a way to either have an anonymous functional 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 a function-for-function of the database object?

For the latter, I had something in my mind that might look like this, but I have no idea how to make the last line.

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

// database.fun(arg).then(function (result) {...});

      

+3


source to share


1 answer


You can define a function and pass its reference as a 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);

      



Also, since getLocationsForCompany()

both getAllLocations()

return a promise, you shouldn't use a $.Deferred()

direct return Promise

return database[fun](arg);

      

+3


source







All Articles