obtain information beyond the prescribed boundaries

Having a slight issue, I am trying to return an array using a function in Angular. I am processing my data within an anonymous function and when I try to return the array, it ends up empty.

I'm not sure what to do...

getCurrentExchangeTo : function(year, month, country){
            var numberDayPerMonth = [
                31,
                28,
                31,
                30,
                31,
                30,
                31,
                30,
                31,
                30,
                31,
                30,
            ];

            var vm = this;
            this.country = country;

            this.getCurrentExchangeFor = [];
            var hello = "gello"

            for(var i = 0; i < numberDayPerMonth.length; i++){
                if((i + 1) === month){
                    for(let j = 1; j < numberDayPerMonth[i]; j++){
                        $http.get('http://api.fixer.io/' + year + '-0' + month + '-0' + j +'?symbols=' + vm.country).then(function (success) {
                            let countryDay = vm.country
                            vm.getCurrentExchangeFor[j] = success.data.rates[countryDay];
                        });
                    }
                }
            }
            return vm.getCurrentExchangeFor
        }

thanks

EDIT Using promise but it's only returning one piece of data

getCurrentExchangeTo : function(year, month, country){

            var def = $q.defer();

            var numberDayPerMonth = [
                31,
                28,
                31,
                30,
                31,
                30,
                31,
                30,
                31,
                30,
                31,
                30,
            ];

            var vm = this;
            this.country = country;

            this.getCurrentExchangeFor = [];
            var hello = "gello"

            for(var i = 0; i < numberDayPerMonth.length; i++){
                if((i + 1) === month){
                    for(let j = 1; j < numberDayPerMonth[i]; j++){
                        $http.get('http://api.fixer.io/' + year + '-0' + month + '-0' + j +'?symbols=' + vm.country).then(function (success) {
                            let countryDay = vm.country
                            vm.getCurrentExchangeFor[j] = success.data.rates[countryDay];
                            def.resolve(success.data.rates[countryDay])
                        });
                    }
                }
            }

            return def.promise
        }

Answer №1

When working with arrays in JavaScript, it's important to use promises effectively. In this case, the array you are returning may be empty because it is being returned before it has been fully populated. To ensure that all data is correctly added to the array before it is returned, consider using Promise.all along with a for loop and HTTP calls.

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

Using Angular's ng-repeat directive to create dynamic directives

Creating a comprehensive view with stacked rows filtered from a JSON array, resonating deeply with complex layering intricacies. Angular novices may find solace in directivizing simplicity while grappling with convoluted alternatives in real-world applica ...

What is the best way to prematurely exit an outer function when there are multiple inner non-blocking function calls?

For the purpose of learning, I am working on creating a basic version of async.parallel. The description from the documentation is as follows: parallel(tasks, [callback]) Run the tasks array of functions in parallel, without waiting until the previou ...

Animation does not occur after the stop() function is executed

My goal is to create a functionality where, upon moving back to the grey content box after leaving the button, the slideUp animation stops and the content slides down again. This works seamlessly with jQuery 1.x (edge), but when I switch to jQuery 1.10, th ...

Retrieve the current URL of an IFRAME

How can I easily retrieve the current URL from an embedded iframe? The user will be navigating through various web pages. I assume that some JavaScript code would be needed for this task. ...

The automatic opening of a modal in a Livewire component is not functioning as expected

I am having trouble displaying a modal when my component initializes. I have tried using $this->emit('show) to open the modal When I add a button in my view, the emit('show') works! However, I want the modal to be automatically shown whe ...

Leveraging Promises in AngularJS to create a chain between two separate controllers

I've developed a provider called MyRestServices to handle my REST-Services: app.provider('MyRestServices', function() { this.baseUrl = null; this.setBaseUrl = function(_baseUrl) { this.baseUrl = _baseUrl; }; this.$get = [' ...

Looking for an alternative to document.querySelectorAll?

My issue involves using querySelectorAll('a') to select all buttons, but I only want to target two specific buttons labeled 'Know More'. How can I achieve this? Below is the code snippet in question: const buttons = document.query ...

Develop an interactive React sidebar with changing elements

I'm in the process of developing a sidebar for a project, with the goal of making it similar to tools like Confluence. This means that we need the ability to rearrange documents and create subdirectory structures by simply moving the documents, with ...

When combining CSS grids, nesting them can sometimes cause issues with the height layout

Check out the code on jsFiddle .component-container { width: 800px; height: 200px; background-color: lightyellow; border: 1px solid red; padding: 10px; overflow: hidden; } .component-container .grid-container-1 { display: grid; grid-tem ...

Exploring Ways to Retrieve Depth Information within three.js

I have come across shaders that can dynamically create outlines around edges based on the difference in depth of pixels. This means that pixels with less depth compared to their adjacent pixels might have a thinner outline or none at all. Examples of such ...

Eliminate placeholder text when the tab key is pressed

I'm currently facing an issue with a textarea that has a placeholder and the Tab key functionality in Internet Explorer. I've included placeholder.js to make it work, but when I repeatedly press the tab key and focus on the textarea, the placehol ...

Tips for displaying autocomplete suggestions as clickable links?

I am new to using Ajax and trying to figure out how to display autocomplete results as clickable links. I have managed to list the related results, but I am struggling to add the links. I believe the links need to be added within the script as an HTML tag. ...

If a value is not printed when a char array is assigned, it will be displayed as empty - in the

Having a bit of a challenge with two functions in my C program that aren't quite cooperating as I had hoped. The first function is supposed to iterate through a CSV file and use `strtok()` to separate tokens based on the ',' delimiter. Each ...

"Unlock the power of Meteor: dynamically serve up the specific range of items

I am facing a challenge with my vast collection of over 5000+ records. I aim to display the records in groups of 10 for easier viewing. How can I update the data dynamically to achieve this? Here is what I have attempted so far: In my server.js file : M ...

When the content div is clicked within the overlay div, the popup will also close

I want to design a pop-up that features a container with a black background and some opacity, where the content of the popup is placed inside. Here's what I have in mind: <button (click)="showPopup = !showPopup">Open popup</button& ...

Is it possible to bundle *.html templates using Require.js Optimizer functionality?

What is the best approach for packaging HTML templates (also known as 'partials') in an Angular.js app when it's concatenated and minified for distribution? Should they be included in the single file, or zipped along with other directories s ...

The Angular router seems to be refusing to show my component

My Angular 2 App includes a Module called InformationPagesModule that contains two lazy load components (Info1 Component and Info2 Component). I would like these components to load when accessing the following routes in the browser: http://localhost:4200/ ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

A step-by-step guide on changing the class of a focused contenteditable element with a button click using jQuery

I need assistance changing the class of an element within a contenteditable div. Here is my current code: <button>swap class</button> <div contenteditable="true"> <h1 class="line-height-1">Your Headline Here</h1> </di ...

Guide to invoking a server-side function through JSON data?

Here is the code I am working on: <script type="text/JavaScript> var myarray = new array(); function getsvg1() { $.ajax({ alert("hello"); type: "post", url: "WebForm1.aspx/getsvg1", ...