Using async functions with Vue.js

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.

Answer №1

The result is simply an empty array.

Yet, due to the nature of JavaScript passing arrays by reference, the array received is actually the exact same array from the function itself. Therefore, once the AJAX call completes, the elements are appended to that original array, leading to the outcome you observe.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic content with Socket.io in Node.js

I am attempting to create a scenario where nodejs triggers an event in an irc chat that causes a html page (Running on *:3000) to execute some JavaScript. However, I am facing an issue where the showDiv(); function is not being executed as expected. Curre ...

Calculating the sum of values in a JSON array using a specific parameter in Typescript

A flat JSON array contains repetitive identifier, categoryId, and category: data: [ { "identifier": "data", "categoryId": "1", "category": "Baked goods", "product": "Aunt Hattie's", "price": "375" } ...

What Causes the "Not a String or Buffer Type" Unhandled Exception?

I've encountered an error that seems to be originating from the following line of code, even though I believe I am following the example correctly (viewable at https://www.npmjs.org/package/aws-sign). Any help or hints would be greatly appreciated. v ...

Encountering some difficulties while setting up my development tool (specifically webpack)

I have embarked on a journey to learn modern JavaScript with the help of Webpack and Babel. As a beginner in this field, my instructor is guiding me through the principles of modern JavaScript by building an app called Forkify - a recipe application. While ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...

What is the solution to resolving the error message "Uncaught ReferenceError: Pusher is not defined" in Vue.js 2?

Whenever I try to launch my application, the console shows the following error: Uncaught ReferenceError: Pusher is not defined and Uncaught ReferenceError: App is not defined Despite running the following commands in my terminal: npm install and ...

Having trouble retrieving data in Next.js and passing it to client components. It's just not functioning as expected

After asynchronously fetching data, I am passing it to a client component as props. However, the state of the client component is not being properly set and displayed. The props are passing correctly, but the state seems to not update for some reason. Ser ...

Ensure that the file exists before including it in the $routeProvider template for ng-include

Using Angular routes, I have set up a system where the slug from the URL determines which file to load. The code looks like this: $routeProvider.when("/project/:slug", { controller: "ProjectController", template: function($routeParams){ return & ...

Utilize JavaScript to substitute font family with a designated class name

After discovering a code snippet that can change font family based on ID, I am interested in implementing it on my website but with a twist - using classes instead of IDs. <!DOCTYPE html> <html> <body> <div class="myP">This is a ...

Setting line chart data for Chart.js

Can you help me troubleshoot an issue I'm facing with creating a dataset for a line chart in Chart.js? Despite having an array of objects, the dataset isn't rendering correctly and I end up with two line charts instead of one. What could be causi ...

Click on a link to navigate to a new page using the useNavigate hook in

I have successfully implemented navigation using the useNavigate hook, but I am wondering if there is a way to open the URL in a new tab instead of the current one. Is this achievable? Here's my code: import { useNavigate } from "react-router-do ...

The onClickOutside feature of VueUse does not respond to the right-click function

Currently experimenting with the onClickOutside method, but encountering an issue where it only responds to clicks outside using the left mouse button. Seeking a way to make it work with the right mouse button as well. Any ideas on how to achieve this? Po ...

After integrating Vue + Inertia into my Laravel 10 project, I encountered an issue where I am receiving an error stating 'autocomplete not a function' when trying to load a Vue

BACKGROUND: My Laravel application is well-established and developed using Laravel, Blade, Javascript, and JQuery. Loading a blade view from the Laravel section of the site does not show any errors in Chrome dev tools. It's important to note that I ut ...

Hiding labels using JQuery cannot be concealed

Why isn't this working? -_- The alert is showing, but nothing else happens. <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeaderContent"> <script type="text/javascript"> if (navigator.userA ...

Guide on Redirecting in Express.js

I am seeking assistance with finding solutions. In short, I have created this API () with username: test and token: test. If the current date is past the meeting time, then open the meeting URL in a new tab. This check should occur every second. ...

Load charts.js synchronously into a div using XMLHttpRequest

At the moment, there is a menu displayed on the left side of the page. When you click on the navigation links, the page content loads using the code snippet below: if (this.id == "view-charts") { $("#rightContainer").load("view-charts.php"); $(thi ...

Can Node.js fetch a PHP file using AJAX?

The Challenge: Greetings, I am facing an issue with my website that features a game created using node.js, gulp, and socket.io. The problem arises when I attempt to call a php file from node.js. While the file returns a success message (echo in the file) ...

axios Error: Unable to assign value to 'username' property because it is undefined

My experience testing the backend API with POSTMAN was successful as everything went smoothly and the response data appeared as follows: {"username":"123","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e4d5d6d7a4838985 ...

Tips for Testing an Ajax jQuery Function Within the document.ready Event

I am in the process of developing a script that utilizes $.ajax to make requests for a json api. My goal is to create unit tests that can verify the results received from the ajax request. For instance, I expect the returned JSON object to contain "items" ...

Managing dynamically appearing elements in Ember: Executing a Javascript function on them

I'm currently working on a project in Ember and facing an issue with calling a JavaScript function when new HTML tags are inserted into the DOM after clicking a button. Below is a snippet of my code: <script type="text/x-handlebars" id="doc"&g ...