What is the best method to utilize a promise to delay the execution of a function until the data is received and stored

Currently, I am facing an issue with my API where the model variable is returning undefined before any data is populated in the return_array.

I am unsure of how to implement promises or another method to ensure that the variable waits for data to be filled correctly, without resorting to using a less-than-ideal $timeout hack.


The problem can be seen here in the chrome inspector (ticker_chart = undefined):

In this scenario, I require ticker_chart to hold off until it receives a value.


The initial function responsible for calling out to a service to retrieve the ticker quote data:

function renderChart(ticker, limit) {
    ticker_chart = TickerChartFactory.returnTickerChartData(ticker, limit);
    console.log('ticker_chart = ',ticker_chart);
}

The complete service function is outlined below:

function returnTickerChartData(ticker, limit) {

    var q = $q.defer();

    var get_data = '';
    if (limit > 0) {
        get_data = '?limit=' + limit;
    }

    ApiFactory.getTickerQuotes(ticker.ticker).success(
        function(data, status, headers, config) {
            if (data.status == 'Success') {
                console.log('REST GET Ticker Chart', 'success');
                var data_array = [];

                for (var i=0; i<data.quotes.length; i++) {
                    data_array.push([data.quotes[i].start_epoch, data.quotes[i].price]);
                }

                var return_array = [{
                    "area": true,
                    "key": "Price",
                    "color": '#BFBFBF',
                    "values": data_array
                }];

                console.log('return_array = ',return_array);
                console.log('q =',q);
                q.resolve(return_array);
                return ticker_chart = return_array;

            } else {
                console.log('failed to REST GET Ticker Chart');
                q.reject('failed to REST GET Ticker Chart');
                return ticker_chart = 'failed to REST GET Ticker Chart';
            }
        }).error(function(data, status) {
            console.log('error in getting REST GET Ticker Chart');
            q.reject('error in getting REST GET Ticker Chart');
            return ticker_chart = 'error in getting REST GET Ticker Chart';
        });
}

The getTickerQuotes function within the ApiFactory:

function getTickerQuotes(ticker) {
    return $http.get('https://www.ourapi.../api/tickers/quotes/'+ticker, {cache: false});
}

What would be the best way to utilize the promise in this context? One alternative approach could involve using a $scope.watch function to await the change in the value of ticker_chart before attempting to render anything.

Answer №1

It seems like you are setting up a promise in the function returnTickerChartData, but there is no return statement to actually return it. To correct this, modify the function as follows:

function returnTickerChartData(ticker, limit) {
    var deferred = $q.defer();
    // API call

    return deferred.promise;
}

Within the getTickerQuotes.success function, simply resolve the promise with the retrieved data. There is no need for the line

return ticker_chart = return_array;
. Instead, update the code as shown below:

function renderChart(ticker, limit) {
    TickerChartFactory.returnTickerChartData(ticker, limit)
        .then(function (result) {
            ticker_chart = result;
            console.log('ticker_chart = ', ticker_chart);
        });
}

EDIT: @Bergi made a valid point in the comments. If the method ApiFactory.getTickerQuotes already returns a promise, utilize that existing promise instead of creating a new one with deferred. Additionally, switch to using

ApiFactory.getTickerQuotes.then()
instead of .success().

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

Struggling to implement .indexOf() in conjunction with .filter()

Hello, I'm new to JavaScript and ES6. Currently, I am working on a react-native app that utilizes Firebase and Redux. One of my action creators acts as a search bar function to fetch data from Firebase. Here's the code I have so far: export cons ...

Issue with React setState not triggering when switching between tabs in Material UI. Attempted to hide using a div with display set to none

Every time I switch between Material UI Tabs, the state gets cleared and does not persist. Check out this link for more information I have attempted different solutions: Using React Context to pass in the React State, but the issue remains unresolved T ...

What could be causing my handle button to slide off the timeline towards the right?

I'm facing an issue with my volume bar component where the slider button is rendering outside of the timeline instead of on top of the progress bar. I need assistance in adjusting its position. // Here is the code for my volume bar component: import ...

Expanding a JavaScript list using HTML inputs

I have a script where a grid dynamically displays a list of words. Is there a way to populate the word list in the grid using HTML? Currently, I am doing this... var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"]; Can additional words be adde ...

How can I extract data from a swiffy animation?

Suppose I am tracking the number of mouse clicks in Flash. To do this, I have utilized the following code: import flash.events.MouseEvent; plus.addEventListener(MouseEvent.CLICK,aaa) var i:int=0; function aaa(e:MouseEvent) { i++; var a:Number ...

Having more than one controller for a single view in AngularJS

Is it possible to use multiple controllers for a single URL view in AngularJS? I am having trouble finding documentation on this. I want to have a controller that switches the page header title on all pages, but some pages already have a controller. app.j ...

Issue: Headers cannot be set again once they have been sent during page reload

Whenever I attempt to refresh a specific page, I encounter an Error: Can't set headers after they are sent. Interestingly, when I click on a link to navigate to that page, the error doesn't occur. I have meticulously reviewed the sequence of even ...

Code snippet for calculating the size of an HTML page using JavaScript/jQuery

Does anyone know of a way to calculate and display the size/weight (in KB) of an HTML page, similar to what is done here: Page size: 403.86KB This would include all resources such as text, images, and scripts. I came across a Pelican plugin that does th ...

Leveraging multer for handling a FormData object in a node.js server

Having trouble with an HTML form that includes two buttons among other text input areas. The front-end javascript code is set up to handle the submit action by creating a FormData object to store the file and sending it via a jQuery AJAX request to a node. ...

Obtain JSON data using jQuery

Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Issue with Snackbar slide transition not functioning properly in mui 5

Transitioning from material-ui 4 to mui 5 has presented me with a challenge. Whenever I try to display my snackbar, an error pops up in the console. After some investigation, I realized that the issue lies within the Slide component that I'm using as ...

Transform a row into a clickable element

I am currently working on a social media platform where users can search for venues stored in the database. In my search.php file, I have implemented a text box that dynamically loads venue names from the database into a venuesearch div as the user types. ...

Javascript's second element does not trigger a click event with similar behavior

I'm currently facing an issue with displaying and hiding notification elements based on user interaction. My goal is to have multiple popup elements appear when the page loads. Then, when a user clicks the ".alert-close" element within one of the popu ...

Encountering issues with creating a session in Selenium/webdriver while utilizing Safari 12

Ever since making the update to Safari 12, my automated scripts have been encountering a new error: SessionNotCreatedError: Request body does not contain required parameter 'capabilities'. (Interestingly, this error is exclusive to Safari and d ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

Maximizing Particle Performance Using JavaScript

I am experimenting with creating particles in JavaScript for the first time, and I'm unsure if the code below is optimized. When I generate 100 particles on the screen, there isn't much of an FPS drop noticeable. However, when multiple clicks o ...

Guide on invoking Objective-C function from JavaScript on iOS

I'm currently working on integrating Highchart into an iOS app. I have a requirement where I need to pass values from JavaScript (HTML file) to an Objective-C method. For example, when a user zooms in on the chart displayed in a UIWebView using Highch ...

Saving an array of key-value pairs in local storage

I'm attempting to save an array in local storage using the following code: var tempval = []; tempval['key'] = 1; localStorage.setItem("Message", JSON.stringify(tempval)); However, when I check local storage, it only sho ...

An expected expression was encountered near the if condition

I am encountering an expression expected error in Visual Studio near if(isNullOr ........ if (value) { if (isNullOrUndefined(x.value) && isNullOrUndefined(x.value2)) { x.minMark + '-' + a + '*' + x.b + ' ' + ...