send back information obtained via an ajax request made by a javascript module

Here is a code snippet featuring an object with a function that makes an AJAX call. The function currently returns an empty array, but we need to figure out how to return the data after receiving the response.

var receivedData = [];
var AjaxUtil = {
    fetchData: function (requestedResource) {
        request
            .get(endpointUrl + requestedResource)
            .set('Accept', 'application/json')
            .end(function (error, response) {
                if(!error) {
                    receivedData = response.body;
                } else {
                    console.log('Error occurred.');
                }
            });

        return receivedData;
}

Answer №1

When the return statement is executed before the request is completed, the data will be empty.

To solve this issue, you can make use of a callback function.

var ApiUtil = {
    fetchAll: function (resourceName, callback) {
        var data = [];
        request
            .get(url + resourceName)
            .set('Accept', 'application/json')
            .end(function (err, res) {
                if(!err) {
                    data = res.body;
                } else {
                    console.log('error');
                }
                callback && callback(data);
            });       
}

Answer №2

If you want to learn more about promises, take a look

Make sure to return a promise, not just a value

fetchAll: function (resourceName) {

    new Promise(
        function(resolve, reject) {
            request
        .get(url + resourceName)
        .set('Accept', 'application/json')
        .end(function (err, res) {
            if(!err) {
                data = res.body;
                resolve(data);
            }else{
                console.log('error');
                reject('error');
            }
        });
        });


    return data;
}

To use this function in your code, follow this pattern:

fetchAll(someParam)
.then(function(result) {
    // do something with the result
});

This approach is helpful when dealing with asynchronous AJAX requests.

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

Exploring the Difference Between $onChanges and $onInit in Angular Components

What sets apart the use of Controller1 compared to Controller2? angular.module('app', []) .component('foo', { templateUrl: 'foo.html', bindings: { user: '<', }, controller: Controller1, ...

When <li> elements are rendered via ajax, it is not possible to attach JavaScript Events to them

Hey there, I've got a drop down menu that's being shown using UL and LI tags. This is generated by a PHP script that echos out: '<li id='. $value .'>'.$value.'</li>' The JQuery function below works perf ...

Unable to modify attribute within $templateCache through an AngularJS Directive

Here is my Directive code: module.directive('iconSwitcher', function() { return { restrict : 'A', link : function(scope, elem, attrs) { var currentState = true; elem.on('click', function() { ...

Enhancing Next.js SEO with 'use client' Metadata

Currently, I am facing an issue with my product page. The metadata for this page is fetched from the backend using an API that retrieves data from a database. To fetch this data and update it on the client side, I am utilizing a custom hook. However, the p ...

The drop-down menu appears to be falling behind the 'content' div element

Whenever I try to hover over the dropdown menu, it frustratingly appears behind the content div that I painstakingly created. Despite all my efforts with z-index adjustments, the issue still persists. Below you'll find all the code for my website, but ...

Creating a JavaScript function using jQuery to calculate the total sum of textboxes with two specified classes

I'm currently attempting to calculate the total of a group of textboxes by utilizing jquery. Each textbox is styled with a class (class1) using bootstrap. To execute the jquery function, I've added an extra class (class2). Below is an example of ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

Error occurs in Angular 10 when reloading IFrame

My goal is to fetch the HTML string from an API and update an iframe with that string. The code works perfectly for the first load, but when the onBtnClick method is triggered a second time, it throws an error: VM3012:1 Uncaught SyntaxError: Identifier &ap ...

AJAX calls experience delays when made in rapid succession

When running an app on my laptop that makes 7 AJAX GET requests simultaneously to a single PHP script, everything works perfectly with all requests returning the desired results. However, after moving the script to a Windows Server running Apache and PHP, ...

Comparing JSON Objects in Javascript

I'm in the process of developing a web application that retrieves data from a server and displays it to the user. The script pulls data from the server every 10 seconds, and if there's any change in the data, it alerts the user. Currently, the co ...

Deletion of input is not permitted

Currently, I have a telephone input field on my form that only allows numbers. I have implemented a simple JavaScript code to enforce this validation. However, the issue I am facing now is that the input box cannot be deleted. <form id="aylikal" action ...

What is the best way for Protractor to effectively wait for a popover to be displayed and verify that it does not contain an empty string?

Whenever you hover over it, this appears - my popup: https://i.sstatic.net/Bm9tC.gif This is what the html looks like before we add the popover to the DOM: <span tariff-popover="popover.car2go.airport" class="ng-isolate-scope"> <s ...

Encountering a 404 XHR Error when attempting to add a component in Angular 4.1.0 within Plunker

Having some trouble setting up Angular 4 on Plunker and adding a new component. The following URL is where I'm working: https://plnkr.co/edit/1umcXTeug2o6eiZ89rLl?p=preview I've just created a new component named mycomponent.ts with the necessar ...

AJAX for efficient storage of various input fields

Currently, I am working on saving input field values dynamically using AJAX in my Laravel framework applications. The issue lies in the fact that all input field names are identical in each table row, causing only the value from the first row to be submitt ...

Submitting a form through AJAX, even when using the $(this) function for another form

Currently, I have a situation where there are two forms present on my page. The first form is located in the footer and serves as a contact page. The second form, named "product-form," is considered to be the main form. Within this form, PHP validation is ...

Remove buttons from carousel elements in React Multi-Carousel

Is there a way to hide the arrows in the react-multi-carousel component? https://i.stack.imgur.com/V1nix.png ...

Script for updating tables using AJAX

I have just completed coding a script for my online tile-based game that dynamically generates the surroundings (tiles) based on your current location in the game area. The game itself is built using a table with multiple cells to hold these tiles. Howeve ...

Nextjs: utilizing static class or employing a use function

Exploring Methods to Create a Tools Class/Function in NextJS I am considering two different approaches for this task. Using Static Class: class Tools { static titleCase(value: string) { return value.charAt(0).toUpperCase() + value.slice(1). ...

Excessive notification events are currently causing a blockage in the Angular app

Currently, I am utilizing Angular 7 in combination with SignalR on the backend for push notifications. At certain times, an overwhelming amount of notifications flood in, causing my application to become completely unresponsive. The SignalR service compon ...

The alignment issue persists in HTML/CSS despite troubleshooting efforts

I am facing a challenge while attempting to center text within a modal window, despite my efforts the text remains uncentered. This is my HTML code: <div ng-init="modalCompassDir()"> <div class="myModal"> <img class='floor ...