Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript代码运行的顺序_Javascript - Fatal编程技术网

javascript代码运行的顺序

javascript代码运行的顺序,javascript,Javascript,我的网页上有以下代码: <script type="text/javascript"> debugger; // 1 var dataClassObj = new DataClassList(); dataClassObj.init(); var viewModel = dataClassObj.getModel(); debugger; // 2 </script&g

我的网页上有以下代码:

   <script type="text/javascript">        
        debugger;  // 1
        var dataClassObj = new DataClassList();
        dataClassObj.init();
        var viewModel = dataClassObj.getModel();
        debugger; // 2
   </script>
}()


当我使用Chrome的开发者工具运行这个程序时,点击调试器点。我原以为它会在1->3->4->2中运行,但它似乎总是按以下顺序运行调试器语句1->4->2->3。我不明白为什么会这样做,我认为Javascript是同步的,所以它会先运行1,然后调用init,触发3,然后调用4,最后调用2。ajax是异步的。它将在其他代码运行(通常)后执行该调用

JavaScript是同步的,除了ajax调用setTimeout()和setInterval()。

在“ajax”中的“A”代表“异步”。在这种情况下,代码是在其他工作完成之后完成的。您需要使用回调来使Ajax之后的事情以正确的顺序运行。该代码应该在
success
property中。您的代码说在ajax调用成功之前不要调用第3部分。
var DataClassList = function () {
};

DataClassList.prototype = function () {
var viewModel;

// private memebers
var init = function () {
        var self = this;
        $.ajax({
            url: "xxx",
            type: 'GET',
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                    // code
                });

                // code
                self.viewModel = viewModel;
                ko.applyBindings(viewModel);
                debugger;  // 3
            },
            error: function(xhr, status, error) {
                $('#lblError').show();
            }
        });
    },
    getModel = function () {
        debugger;  // 4
        return viewModel;
    };

// public members
return {
    init: init,
    getModel: getModel
};