0

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.

1
  • 1
    @JosephSilber already gave the right answer, but as a little extra, you could return result.slice() which create a copy of the array, in this context it'll be your snapshot. Then you should see it's indeed empty :) Commented Mar 5, 2017 at 21:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.