How can I wait until my AJAX request is complete?

Refresh

December 2018

Views

16.8k time

1

So, I have an init function that runs when the DOM is fully loaded:

function init() 
{
    TerrainObj.load_terrain();
    TerrainObj.generate_display_layer(PlayerObj);
    GameObj.update();
    ScreenObj.draw_screen(TerrainObj);
    ScreenObj.update_screen(TerrainObj);
    mainloop();
}

The very first method, TerrainObj.load_terrain(), makes an AJAX requestL:

load_terrain: function()
{
    var settings = {
        type: "GET",
        url: "data/map.txt",
        aysnc: false
    };

    $.ajax(settings).done(function(result) 
    {
        this.terrain = result.split("\n");
        for (var i = 0; i < this.terrain.length; i++)
        {
            this.terrain[i] = this.terrain[i].split("")
        }
        console.log(this.terrain);
    });
}

The problem is that, in our init() function, most of the methods that follow TerrainObj.load_terrain() require the presence of the TerrainObj.terrain array, but they are called before the AJAX request can complete and that variable is populated. I put a little message out when each function runs to check the order, and I get this:

Ran TerrainObj.load_terrain()
Ran ScreenObj.draw_screen()
Uncaught TypeError: Cannot read property '0' of undefined 
[Array[55], Array[55], ... ]

So as you can probably see, ScreenObj.draw_screen, which needs TerrainObj.terrain, has run before the request can complete, and there's a TypeError when it tries to reference our object. It's not ready yet! The very last message is the console.log() from the load_terrain method, indicating that the .done function runs afterwards.

What can I do to wait until the AJAX request is complete before continuing on with my program?

njp

2 answers

1

Проверьте комментарий в разделе ниже в блоке кода

    $.ajax(settings).done(function(result) 
    {
        this.terrain = result.split("\n");
        for (var i = 0; i < this.terrain.length; i++)
        {
            this.terrain[i] = this.terrain[i].split("")
        }
        /*******************************************/
        //Place a new function call here, to the function that contains the calls to your 
        //functions, or other logic, that require the array to be populated.
        /*******************************************/
    });
4

Javascript является событийным языком. Вы не имеете MainLoop, но у вас есть события, которые вызывают то, что происходит.

Здесь, завершение вашего АЯКС вызова запускает subsquent Настройка местности. Таким образом, отдельные функции в двух:

init: function() 
{
    TerrainObj.load_terrain();
},
init_terrain: function()
{
    TerrainObj.generate_display_layer(PlayerObj);
    GameObj.update();
    ScreenObj.draw_screen(TerrainObj);
    ScreenObj.update_screen(TerrainObj);
    mainloop();
},
load_terrain: function()
{
    var settings = {
        type: "GET",
        url: "data/map.txt",
        aysnc: false
    };

    $.ajax(settings).done(function(result) 
    {
        this.terrain = result.split("\n");
        for (var i = 0; i < this.terrain.length; i++)
        {
            this.terrain[i] = this.terrain[i].split("")
        }
        this.init_terrain();
    });
}