In my Vue.js component, I have the following code snippet:
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;
}
}
}
Although this code is functioning properly, I'm puzzled by one aspect:
Why does the search()
method not immediately return an empty array even before the results of $.getJSON()
, which is asynchronous, are available? It's actually surprising to me that it waits for the callback function to finish execution before returning.