简体   繁体   中英

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.

Thanks for the help!

callback is a local variable. It only exists inside function (query, callback) { /* ... */ } .

You can't use it from outside that function (ie in the anonymous function you pass to 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. 1. string 2. function.

So when you are calling that module.

it should be:

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

Hope this help you.

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