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):

https://i.sstatic.net/0x4JH.png

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

Is there a neat method in React and Material UI for de-structuring the props that I am passing to useStyles?

When passing props to useStyles based on the Material docs, our code looks like this: const useStyles = makeStyles({ // style rule foo: props => ({ backgroundColor: props.backgroundColor, }), bar: { // CSS property color: props => ...

Unit testing with Jest leading to the error message "MongoDB Error: topology was destroyed"

Currently, I am using Jest to execute unit tests for my Node.js application. To ensure that the mongoose connection is closed properly after each test, I have set up a setup script that calls the afterAll() function. However, I am encountering an error m ...

Tips for displaying a combobox popover from @reach/combobox within a MUI dialog element

I've been attempting to integrate a map from the Google Maps API and a combobox popover from @reach/combobox within a MUI dialog component. However, I've encountered an issue where the combobox popover isn't displaying. After some investigat ...

How can you make the table rows in jQuery scroll automatically while keeping the table header fixed in

Many solutions exist for making the header fixed and the table scrollable using code samples or plugins. However, my specific goal is to have the table data rows scroll automatically once they are loaded while keeping the header fixed in place. Is there a ...

Guide on incorporating Vue components: implementing component 2 within the template of component 1

I'm a Vue beginner and struggling with how to use one component within the template of another or how to combine them in HTML. I've tried looking through the documentation and Stack Overflow but can't seem to figure it out. Currently, I am ...

Keep things in line with async functions in Node JS

Hello, I am just starting out with NodeJs and I have a question. I am trying to push elements into an array called files based on the order of the urls provided, but it seems like I'm getting a random order instead. Below is the code I've been wo ...

Fade out the div element when clicked

For my game project, I needed a way to make a div fade out after an onclick event. However, the issue I encountered was that after fading out, the div would reappear. Ideally, I wanted it to simply disappear without any sort of fade effect. Below is the co ...

Control the start and stop of an Express.js app in Node.js using PHP

I'm currently developing a web service using express.js in the node.js npm environment. In order to deliver this project to my client, I need to create a controller file that allows me to start and stop the server without having to use the command pr ...

Stopping form submission on a jQuery form

I am in the process of implementing a password control feature on a login form using jQuery and ajax. This is the current script I have: $(document).ready(function() { $("#login-form").submit(function(e) { var csrftoken = getCookie('csr ...

Is the tab not displaying correctly when using Bootstrap 5 button functionality?

With Bootstrap 5, I have a modal that contains two tabs for login and register. However, I am facing an issue where the tab is not displaying correctly based on the button click. The desired behavior is that clicking on the login button should activate th ...

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

How can you organize an array into rows and columns for easier viewing?

Hopefully everything is clear. I am open to making changes if needed to address any important points. In one of my components, the array items are displayed within cards as shown below: <b-card-group deck class="mb-3"> <b-card border-variant ...

What is causing the issue with dynamic special characters not functioning properly in my React router?

I am working with 3 components named App.js, SearchCategoryPage.js, and Home.js. However, when I click on the search icon, it does not navigate me to the search page. What could be the reason for this issue? App.js const outlet_id = useSelector((state) =& ...

Why does Drupal's Advagg display several css and js files?

After installing the Advag module, I noticed that it is combining files, but there seems to be an issue: <link type="text/css" rel="stylesheet" href="/sites/default/files/advagg_css/css__sqX0oV0PzZnon4-v--YUWKBX0MY_EglamExp-1FI654__IOPiOtulrIZqqAM0BdQC ...

Switching from using jQuery to Mootools in a short script that helps to balance the heights of

I have a simple script that I frequently use in jQuery to make boxes equal heights. Now, I need to convert it to mootools for a new project where the boxes will be floated left at thirds using style sheets. <div id="box1" class="equals">content he ...

Error: Child component received an undefined prop

Within my parent component, I have three child components. The first child component is a form that, upon submission, passes data to the second and third child components through props via the parent component. However, in one of the child components, the ...

What is the best way to prevent duplicates in a Material-UI dropzone area?

Currently, I am utilizing the Material-UI Dropzone component from https://yuvaleros.github.io/material-ui-dropzone/ and my goal is to prevent users from uploading duplicate files that have been previously uploaded. I attempted using an onchange function t ...

Why does attempting to access an undefined property not trigger an error?

I am curious to know why var myVar = unDef; may trigger a ReferenceError, while var myObj = {}; var myVar = myObj.unDef; runs smoothly? It simply returns undefined without any runtime issues. Despite both not being defined. ...

Using Angular: connecting $viewContentLoaded to manually initiate app bootstrapping

I have an Angular module that I am bootstrapping manually and attempting to access its $rootScope to add an event listener for $viewContentLoaded. Below is the code snippet: angular.bootstrap(el, [appname]); //////////////////////////// Fixing links cons ...

When using Javascript template literals, they function properly when assigned to a variable, but they do not work when included in a JSON

Trying to get a grasp of Javascript. Let's say I have a variable declared with template literals: var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.` This functions correctly as sh ...