Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous function argument

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) {...});
like image 867
Decay42 Avatar asked Sep 23 '26 21:09

Decay42


1 Answers

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);
like image 141
Satpal Avatar answered Sep 25 '26 09:09

Satpal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!