Looping through a set of API calls using JavaScript Web API

Currently, I am in the process of developing an application using angularjs and ionic. Within this app, I have an array containing IDs, and my objective is to retrieve their corresponding names. To achieve this, I attempted the following code snippet:

var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
var arrayWithNames = [];

for (var j = 0; j < arrayWithIds.length; j++) {
    ResourceService.get(arrayWithIds[j]).then(function(resource) {
        arrayWithNames.push(resource.Name);                  
    },function(error) {
        alert(error.message);        
    });               
}

$scope.resources = arrayWithNames;

Throughout debugging, everything appears to be functioning correctly as I consistently receive the name values. However, upon examining $scope.resources, it shows up empty along with the arrayWithNames array.

Is there something crucial that I may be overlooking? What could possibly be causing this issue?

Thank you for your assistance.

Answer №1

The ResourceService.get() function is asynchronous, operating as a Promise. Consequently, the line

$scope.resources = arrayWithNames;

is being executed prior to the callback from ResourceService.get().

To resolve this issue, you can eliminate the use of arrayWithNames and directly push data to $scope.resources:

var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
$scope.resources = [];

for (var j = 0; j < arrayWithIds.length; j++) {
    ResourceService.get(arrayWithIds[j]).then(function(resource) {
        $scope.resources.push(resource.Name);                  
    },function(error) {
        alert(error.message);        
    });               
}

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

What is the reason behind Meteor automatically updating a record without the need to run a "Meteor.call" function for an update?

I am currently developing a Meteor.js application and while I have grasped the basic concepts of Meteor, I feel like I might be missing something when it comes to its reactivity principles. Using angular-meteor, I am utilizing a $scope variable in my view ...

`Loading CSS and JS files in node.js: A step-by-step guide`

I've searched through numerous similar questions without success, so I'm reaching out for help. My folder structure looks like this: Source Code Frontend Graphs.html Graphs.css Temperature.js Server_Backend server.js I aim ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Creating a unique theme export from a custom UI library with Material-UI

Currently, I am in the process of developing a unique UI library at my workplace which utilizes Material-UI. This UI library features a custom theme where I have integrated custom company colors into the palette object. While these custom colors work perfe ...

I encountered an issue when attempting to execute an action as I received an error message indicating that the dispatch function was not

I just started learning about redux and I am trying to understand it from the basics. So, I installed an npm package and integrated it into my form. However, when I attempt to dispatch an action, I encounter an error stating that 'dispatch is not defi ...

Angular $watch event does not trigger when there is a change in window.getSelection().anchorNode

My role is to monitor changes in user-selected text. I activate based on the DOM element being highlighted. Here is the function I use for this purpose: $scope.$watch(function(scope) { return window.getSelection().anchorNode }, function() { cons ...

reducing the dimensions of the expanding panel in Material UI

I am facing a challenge which requires me to reduce the size of the expansion panel when it is open or expanded. I checked the elements and styles tab, but it seems that we need to override the styles. Has anyone dealt with this scenario before? Here is a ...

Display and conceal different sections using hyperlinks

Hey there, I'm back with another issue related to this code snippet on jsfiddle: https://jsfiddle.net/4qq6xnfr/9/. The problem I'm facing is that when I click on one of the 5 links in the first column, a second div appears with 3 links. Upon clic ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

Exporting modules in Node.js allows you to use functions

Can you explain why this code snippet is successful: exports.foo = 'foo'; var bar = require('./foo'); console.log(bar); // {foo: 'foo'} While this one fails to produce the desired output: var data = { foo: 'foo' ...

What are some ways to avoid the use of underline and slash symbols in material-ui/pickers?

Is there a way to remove the underline and slash characters that separate day, month, and year in the material ui pickers for version mui version 4? <KeyboardDatePicker margin="normal" id="date-picker-dialog" label="Dat ...

Sending AJAX Responses as Properties to Child Component

Currently, I am working on building a blog using React. In my main ReactBlog Component, I am making an AJAX call to a node server to get back an array of posts. My goal is to pass this post data as props to different components. One specific component I h ...

Trouble arises when implementing AJAX in conjunction with PHP!

I am facing an issue with my PHP page which collects mp3 links from downloads.nl. The results are converted to XML and display correctly. However, the problem arises when trying to access this XML data using ajax. Both the files are on the same domain, b ...

What is the best way to automatically remove a Firebase database entry when a user has been inactive for a period of time, without logging out but simply not accessing the page for an extended duration?

Currently, when a user clicks 'logout', their session is terminated, and a database entry is removed. All other users can see that database entry, so the objective is for users to view each other's data only while they are logged in. For in ...

Exploring Angular: tackling multiple controllers in a single view or route

We are currently in the process of developing a large Single Page Application (SPA). The application is structured using widgets/components, each with its own template and controller. These components can be nested within the same route. For instance, with ...

Angular does not select the variable_name within the $scope

Here is the HTML code I have written. <div class="container" ng-app="mintcart"> <div class="panel panel-default" ng-controller="categoriesctrl"> <input type="hidden" ng-model="session.sid" value="<?php echo session_id();?>"/&g ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

Issues arising while passing a parameter to a Node.js module

I've been struggling with passing a variable to a module. In my node.js setup, I have the following structure: The main node.js server (server.js): // modules ================================================= var express = require('expr ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...