如何让JQuery JSON函数在JavaScript之前运行

时间:2018-11-24 05:36:26

标签: javascript jquery

我以前从未使用过JQuery。我试图打开一个json文件,并将一些值存储在一个名为points的变量中。当我的代码运行时,它将在其余javascript之后运行Jquery,但我需要在之前运行它。有人可以解释一下它的顺序如何工作以及如何更好地组织它。

var points = [];

$.getJSON("3_clusters.json", function(json){
    console.log('Starting collating points')
    for (var row=0; row<json.X.length; row++){
        points.push([json.X[row][0], json.X[row][1]]);
    }
    console.log('Finished collating points')
});

console.log("This should run after json loaded");

它应该创建points变量,执行getJSON内容,然后输出控制台消息。

1 个答案:

答案 0 :(得分:3)

有多种方法可以做到:

  1. 使用回调函数:
var getJSON = function (callback) {
    var points = [];

    $.getJSON("3_clusters.json", function(json){
        console.log('Starting collating points')
        for (var row=0; row<json.X.length; row++){
            points.push([json.X[row][0], json.X[row][1]]);
        }
        console.log('Finished collating points')

        callback();
    });

};

getJSON(function () {
    console.log("This should run after json loaded");
});
  1. 使用异步函数:
(async function () {
    var points = [];

    var json = await $.getJSON("3_clusters.json");

    console.log('Starting collating points')
    for (var row=0; row<json.X.length; row++){
        points.push([json.X[row][0], json.X[row][1]]);
    }
    console.log('Finished collating points');

    console.log("This should run after json loaded");
}());
  1. 使用Promise
var task = new Promise(function (done) {
    var points = [];

    $.getJSON("3_clusters.json", function(json){
        console.log('Starting collating points')
        for (var row=0; row<json.X.length; row++){
            points.push([json.X[row][0], json.X[row][1]]);
        }
        console.log('Finished collating points')

        done();
    });
});

task.then(function () {
    console.log("This should run after json loaded");
});