jQuery.get executes after all rest of the function

1

Running this code the sequences of alerts I have is begin, outside, final e inside , how to solve this ??

        addLine(){
            alert('begin')
            jQuery.get('database/addClube/'+this.clube);

            jQuery.get('database/getClubes', function(data){
                this.list = data;
                console.log(this.list);
                alert('inside')
            });

            console.log(this.list);
            alert('outside')
            for(item in this.list){
                //alert(item);
            }

            this.clube = '';
            alert('final')
        },
    
asked by anonymous 09.08.2017 / 22:49

2 answers

1

You could use it like this, because the get may take a while to bring the data depending on the volume:

         addLine(){
            alert('begin')
            jQuery.get('database/addClube/'+this.clube);

            jQuery.get('database/getClubes', function(data){
                this.list = data;
                console.log(this.list);
                alert('inside');

                for(item in this.list){
                    //alert(item);
                }
            });

            this.clube = '';
            alert('final')
        },
    
09.08.2017 / 22:53
0

The jQuery.get () method is, by default, asynchronous, that is, it creates a new thread to download the page in question and continues the javascript. The new thread then responds to the download by calling its function there.

You can use the jQuery.get(settings) method, passing all parameters through a object and one of them being the async parameter. Passing false to it, the request is not made on another thread and thus waits for the return to continue its script, however it can detract from the user experience when using the page:

        jQuery.get({
            async: false;
            url: 'database/getClubes',
            success: function(data) {
                this.list = data;
                console.log(this.list);
                alert('inside');

                for(item in this.list){
                    //alert(item);
                }
            },
        });

Or you could try it this way:

    jQuery.ajax({
        url: 'database/getClubes',
        success: function(data) {

            this.list = data;
                console.log(this.list);
                alert('inside');

                for(item in this.list){
                    //alert(item);
                }

        },
        error: function(data) {

            // handle the response
            // show the UI again

        }
    }); 

Do the same for the first% including%, however I recommend using get() for the modifications, such as adding or updating the database.

    
09.08.2017 / 23:17