jQuery函数在内部函数完成之前完成运行

时间:2020-08-18 13:19:23

标签: javascript jquery ajax

当前,getAllPatientInfo将在加载内部函数(getPatientName和getPatientReport)之前完成加载。因此,加载页面时,我检索到的值是不确定的。有什么办法可以解决这个问题?

我在getPatientName和getPatientReport上都尝试过console.log,它们能够检索信息,只是不能在getAllPatientInfo函数中使用时

function getPatientName(userId) {
    console.log("retrieving patient name...")
    $.ajax({
        type: 'GET',
        url: userURI,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            userInfoArray = data;
            for(i = 0; i < userInfoArray.length; i++) {
                if (userId == userInfoArray[i].user_id) {
                    patientName = userInfoArray[i].full_name;
                }
            }
        }
    });
}


function getAllPatientInfo() {
    console.log("retrieving all patient infomation...")
    $.ajax({
        type: 'GET',
        url: patientURI,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            patientInfoArray = data;
            console.log(patientInfoArray)
            $('#patientCard').html('');
            for (i = 0; i < patientInfoArray.length; i++) {
                getPatientName(patientInfoArray[i].user_id)
                getPatientReport(patientInfoArray[i].patient_id)             
                $('#patientCard').append("<article> <div class='text'><h3>"+patientName+"</h3><p>x</p>"+
                  "<p><b>Latest Update</b></p><p>FT4:x</p><p>TSH: x</p>"+
                  "<a class='button' href='patient-info-doctor.html' >More Details</a>"+
                  "<a class='button' href='#'>Graph</a></div></article>");
            }
        }
    });
}


function getPatientReport(patientId) {
    console.log("Retrieving Patient Report...")
    $.ajax({
        type: 'GET',
        url: reportURI,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            reportArray = data;
             for(i = 0; i < reportArray.length; i++) {
                if (patientId == reportArray[i].patient_id) {
                        valueFT4 = reportArray[i].FT4,
                        valueTSH = reportArray[i].TSH,
                        latestUpdate = reportArray[i].timestamp
                    
                }
            }
        }
    });
}

$(window).on('load', function() {
    getAllPatientInfo();
   });

0 个答案:

没有答案