简体   繁体   English

带参数的Javascript回调函数

[英]Javascript callback function with parameter

The call: 电话:

Query.GetDepartments(AcademicYears, function (result) {
                    console.log(result)
                })

The function: 功能:

exports.GetDepartments = function (callback, AcademicYears) {
    CountAcademicYears = Object.keys(AcademicYears).length;
    switch (CountAcademicYears) {
        case 1:
            AcademicYear1 = AcademicYears[0].Year;
            AcademicYear1 = String(AcademicYear1);
            query = "SELECT [p_departement], [depcode], [departement], [schooljaar] FROM [SA_Departement] WHERE schooljaar='" + AcademicYear1 + "'";
            console.log(query);
            (async function () {
                try {
                    let result = await globalConnectionInfordat.request()
                        .query(query);
                    callback(result.recordset);
                } catch (err) {
                    console.log(err);
                }
            })();
            break;
        ..........

    }
}

This gives me this error: 这给了我这个错误:

'Incorrect syntax near the keyword \'function\'.',

For some reason, the string isn't read out alright(I think)? 由于某种原因,该字符串未正确读出(我认为)? Any ideas? 有任何想法吗?

I just need to know how to pass an argument to the function? 我只需要知道如何将参数传递给函数?

EDIT 编辑

I had to move the words around for some reason: function (Academicyears, callback) is working. 由于某些原因,我不得不将单词移开:函数(Academicyears,回调)正在运行。

Thanks for the help! 谢谢您的帮助!

callback is a local variable. callback是一个局部变量。 It only exists inside function (query, callback) { /* ... */ } . 它仅存在于function (query, callback) { /* ... */ }

You can't use it from outside that function (ie in the anonymous function you pass to ExecuteSql ). 您不能从该函数外部使用它(即,在传递给ExecuteSql的匿名函数中)。

You would need to create another reference to that function and then use that name: 您将需要创建对该函数的另一个引用,然后使用该名称:

this.ExecuteSql("SELECT ...", function a_named_function (result) {
            a_named_function(result);
        });

… but recursively calling that function makes no sense. …但是递归调用该函数没有任何意义。

As per definition of "ExecuteSql", it accepts 2 param. 按照“ ExecuteSql”的定义,它接受2个参数。 1. string 2. function. 1.字符串2.函数。

So when you are calling that module. 因此,当您调用该模块时。

it should be: 它应该是:

  this.ExecuteSql("your string", function (result) {
                   console.log(result);
                });

Hope this help you. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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