如何防止JavaScript函数在前一个函数执行完毕之前运行?

时间:2019-07-12 17:54:52

标签: javascript function

我的JavaScript中有两个函数可用于一个简单的Web应用程序。一个函数从.JSON文件收集数据,另一个函数设置要显示的文本。因为文本试图在数据收集完成之前生成,所以文本根本无法生成。

我已经使用窗口警报来查看何时运行不同的进程,并发现,尽管这些函数按顺序开始执行,但第二个函数甚至在第一个函数中内置第一个对象之前就开始了。

'''JavaScript

var arr = []

//Data Collection
function buildData() {
    alert("buildData");
    d3.json("data.json", function (error, data) {
        if (error)
            throw error;
        $.each(data, function (i) {

            arr.push(makePerson(data[i].name, data[i].jobTitle, data[i].Company, data[i].Experience, data[i].School, data[i].major, data[i].Email, data[i].LinkedInURL));
        });
        for (i = 0; i < 4; i++) {
            alert(arr[i].name);
        }
    });
}

// Build Function
function makePerson(name, jobtitle, exp, company, school, major, email, url){
    return{
        name,
        jobtitle,
        exp,
        company,
        school,
        major,
        email,
        url
    }
}

function addText(iter) {
    iterString = iter.toString();
    alert("addText");


}


$(document).ready(function () {
    buildData();
    addText(1);
});

'''

'''JSON

[
  {
    "name": "Steve Smith",
    "jobTitle": "Project Manager",
    "Company": "Front End Dev Co",
    "Experience": "3 years",
    "School": "UW",
    "Major": "Marketing",
    "Email": "steve@fedc.com",
    "LinkedInUrl": "steve.linkedinprofile.com"
  },
  {
    "name": "Aaron Katz",
    "jobTitle": "Full Stack Developer",
    "Company": "Web Sites and More",
    "Experience": "5 years",
    "School": "SU",
    "Major": "Computer Science",
    "Email": "aaronNotMyEmail@uw.com",
    "LinkedInUrl": "aaron.linkedinprofile.com"
  },
  {
    "name": "Kyle Hendricks",
    "jobTitle": "Starting Pitcher",
    "Company": "Chicago Cubs",
    "Experience": "12 years",
    "School": "USC",
    "Major": "Pitching",
    "Email": "kyleH@cubs.com",
    "LinkedInUrl": "kyle.linkedinprofile.com"
  },
  {
    "name": "Michael Jordan",
    "jobTitle": "Point Guard",
    "Company": "Chicago Buls",
    "Experience": "20 years",
    "School": "UNC",
    "Major": "Trash Talking",
    "Email": "mJordan@bulls.com",
    "LinkedInUrl": "mJordas.linkedinprofile.com"
  }
]

'''

按原样,该代码应该显示窗口警报:“ buildData”,“ Steve Smith”,“ Aaron Katz”,“ Kyle Hendricks”,“ Michael Jordan”,“ addText”。

它按原样提供:“ buildData”,“ addText”,“ Steve Smith”,“ Aaron Katz”,“ Kyle Hendricks”,“ Michael Jordan”。

0 个答案:

没有答案