pharkasbence
pharkasbence

Reputation: 987

Vue.js and async function call

I have the following Vue.js component:

module.exports = {
    data: function () {
        return { 
             searchText: "",
             searchResult: []
        }
    },
    watch:
    {
        searchText: function() {
            this.searchResult = this.search()
        }
    },
    methods:
    {
        search: function()
        {
            var result = [];
            var _self = this;

            $.getJSON("data/data.json", function(json) {                   
                $.each(json, function(index, obj) {
                    if (_self.searchText.length > 0 && obj.text.indexOf(_self.searchText) != -1)
                        result.push(obj);
                }, this);
            });

            return result;
        }
    }
}

This code works well, but I don't understand why:

Why search() doesn't return an empty array without waiting for the result of $.getJSON() which is an asynchronous function? Surprisingly (for me), it only returns after the callback function is completed.

Upvotes: 0

Views: 1147

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219920

It indeed only returns an empty array.

However, since arrays in JS are passed by reference, the array you get back is the very same array from within the method. So when the AJAX request resolves, the items are added to that array, which is what you subsequently see.

Upvotes: 2

Related Questions