匿名函数参数

时间:2017-07-10 09:21:28

标签: javascript apply anonymous-function

我的代码中有一个看起来像这样的部分

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

但是,因为它基本上是两次相同的东西,只是使用不同的ajax调用 - 是否有任何方法可以使用匿名函数部分

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

声明为真实函数然后只是在.then()子句中调用,或者我可以以某种方式提供数据库对象的被调用函数吗?

对于后者,我脑子里有一些看起来像这样的东西,但我不知道怎么做最后一行。

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

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

1 个答案:

答案 0 :(得分:3)

您可以定义一个函数并将其引用作为成功回调处理程序

传递
std::vector<int> numbers;

此外,当//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); getLocationsForCompany()返回承诺时,您不应该使用getAllLocations()直接返回承诺

$.Deferred()