简体   繁体   中英

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) {...});

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM