【问题标题】:JavaScript Array not updating when using it in callback method [duplicate]在回调方法中使用JavaScript数组时不更新[重复]
【发布时间】:2020-11-17 14:27:34
【问题描述】:

我在 javascript 函数中有一个本地数组。我正在迭代一个有选择(组合框)的表。对于每个选择,我都在对 C# 函数(在循环中)进行 ajax 调用。在收到结果后的回调方法(内部函数)中,我将其添加到本地数组中。然后在遍历表行之后,我使用数组调用另一个函数。但是这个数组仍然是空的。 当我更改表格的任何组合框的选定项时,将调用具有本地数组的函数。

当我调试它时,我可以看到收到的 ajax 调用项已添加到回调函数中的数组中。但是在循环遍历表后调用另一个函数时,数组仍然是空的。

我怎样才能让它工作,以便在循环遍历表后调用函数时填充数组?

这是函数:

function doCourseCheck() {
    var errors = [];
    var chosenSubjectTypes = []; //this is the array I want to fill

    var table = document.getElementById('choiceTable');
    var selectId = 0;
    var subjectTypeReceived = function (result) {
        chosenSubjectTypes.push(result); //array is filled in the callback function (inner function)
    }


    //looping through the table
    for (let j = 0; j < table.rows.length; j++) {
        if (j === 0 || j === 3) {
            continue;
        }

        var comboBox = document.getElementById('select_' + selectId); 
        var subjectName = comboBox.options[comboBox.selectedIndex].text;
        if (subjectName !== "") {
            //in this function the ajax call is done and the result is given to the callback function
            getSubjectType(subjectName, subjectTypeReceived);
        }

        selectId++;
    }
    //here the filled array should be used but it stays empty
    checkCourseChoices(errors, chosenSubjectTypes);
    showErrors(errors);
}

这是完成 ajax 调用的函数:

function getSubjectType(subjectName, callback) {
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        data: { name: subjectName },
        dataType: 'json',
        url: "/Subjects/Choose?handler=SubjectType",
        cache: false,
        success: function (result) {
            callback(result);
        }
    });
}

【问题讨论】:

  • 数组不会“保持为空”。它被填满,但稍后。因为ajax调用是异步的。当你调用它并尝试使用它时,它仍然是空的。

标签: javascript arrays callback


【解决方案1】:

您不能混合使用同步和异步代码。同步代码将始终在异步代码之前完全执行,无论您想对数组做什么,都必须在回调中进行。换句话说,你必须这样说:

checkCourseChoices(errors, chosenSubjectTypes);
showErrors(errors);

subjectTypeReceived 函数内部

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2017-05-10
    • 2020-09-18
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 2015-08-23
    相关资源
    最近更新 更多