Encountering an error in AngularJS $http calls while trying to loop: TypeError - object is not functioning

Currently, I am in the process of automating the population of my app's database with Dummy Data to eliminate the manual task of adding users, friends, and more. To achieve this, I have implemented nested AngularJS $http requests that interact with my backend API/Rest service...

Everything has been functioning correctly up to this point, but now I face the challenge of looping asynchronous calls, like the example below where the 3rd nested $http call is illustrated.

// 3. Create Auto Friend For that User
for (var i = 1; i < 6; i++) { // 6 is just a given number, it could be 1 or 100....
   ($http({method: 'POST', url: '/path/to/rest/friend', data: {"name":"Auto Friend " + i}})
      .then(function (response) {
         console.log("friend created");
         console.log(response);

      }, function () {
         console.log('Whoops...');
      }))(i); // THIS IS LINE 69
}

However, I've encountered an error message...

TypeError: object is not a function
    at http://localhost:9000/assets/js/src/app/auth/controllers/AuthCtrl.js:69:40
    at wrappedCallback (http://localhost:9000/assets/js/vendor/bower/angular/angular.js:10549:81)
    at http://localhost:9000/assets/js/vendor/bower/angular/angular.js:10635:26
    at Scope.$eval (http://localhost:9000/assets/js/vendor/bower/angular/angular.js:11528:28)
    at Scope.$digest (http://localhost:9000/assets/js/vendor/bower/angular/angular.js:11373:31)
    at Scope.$delegate.__proto__.$digest (<anonymous>:844:31)
    at Scope.$apply (http://localhost:9000/assets/js/vendor/bower/angular/angular.js:11634:24)
    at Scope.$delegate.__proto__.$apply (<anonymous>:855:30)
    at done (http://localhost:9000/assets/js/vendor/bower/angular/angular.js:7635:45)
    at completeRequest (http://localhost:9000/assets/js/vendor/bower/angular/angular.js:7801:7)

I've made some adjustments to my code without success so far. It seems like my approach might be flawed rather than the code itself. If anyone has any suggestions or recommendations on how to resolve this issue, please share your thoughts!

Answer №1

It seems like I have figured out the solution on my own, it turns out I forgot to enclose the code in a function...

for (var i = 1; i < 6; i++) { // The number 6 is just an example, it could be any value...
   (function(i){
     http({method: 'POST', url: '/path/to/rest/friend', data: {"name":"Auto Friend " + i}})
      .then(function (response) {
         console.log("friend created");
         console.log(response);

      }, function () {
         console.log('Oops...');
         });
      })(i);
}

Next time, I will make sure to double-check before posting. Appreciate the feedback!

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

How to get the initial item from an API using JavaScript mapping

When mapping my arrays, I usually use the following code: moviesList.map(movie => <MovieCard movieID={movie} key={movie} However, there are instances where my API returns multiple results. Is there a way to modify my .map function to display only t ...

Cleaning up checkbox names by removing unnecessary characters

I'm having an issue with unnecessary characters in the names of checkboxes. There is a certain line var string = "<div class="blblb"><input type="checkbox" name="dasdasads"><input type="checbox" name="adsdsada"></div>"; The ...

Automatically inserting a row into an HTML table

My table structure looks like this: <form name="frm_data_nasabah2" method="post" enctype="application/x-www-form-urlencoded" action="<?php echo $page_action;?>"> <table class="table table-bordered table-hover" id="tab_logic_ ...

Guide on displaying an array object in MongoDB using React

I'm having trouble figuring out how to display certain data from my MongoDB schema in a React component. Here is my MongoDB schema: const postSchema = new mongoose.Schema({ userID: { type: String }, dateTime: { type: Date, default: Date.now } ...

Is there a way to showcase the legend in a pie chart with two columns?

Is there a way to show the legend in two columns within the pie chart? Here is my JSfiddle link for reference: http://jsfiddle.net/Cp73s/2185/ itemStyle: { width:200, font: 'Helvetica Neue' ...

How to calculate large integer powers efficiently in JavaScript using the mod

I'm currently on the lookout for a reliable JavaScript algorithm as I attempted to implement one using node.js : function modpow_3(a,n, module){ var u = BigInt('1'); var e = equals(a, u); if( e) return a; if(equalsZero(a)) return a; if(pair ...

Experiencing a disappearing session on Express.js happens approximately every 3 minutes (I can relate to this problem as

I am encountering a similar issue to the question mentioned here: Express.js session lost after about 3 minutes Unfortunately, I have not been able to find a solution yet. This is my Session Code: app.use( session({ secret: 'secret', resave ...

How can I make a page scroll to the center when clicking on a carousel?

My goal is to create a webpage where clicking on the carousel will center it on the page. A great example of this functionality can be seen on the Studio New Work website (). As I am still in the process of learning JQuery, I have not yet mastered all the ...

What is the method used for defining an element within an array in JavaScript?

As I am new to JavaScript, I find myself trying to organize callbacks within an array. An example of what I have been working on: items = [ "test" = async message => { let userCoins = editCurrency('fetch', message.guild. ...

Proper utilization of ngIf in conjunction with mat-cell

I am attempting to show a specific value only if the item possesses a certain property, but I keep seeing [object Object] instead. Here is my current method: <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDe ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

The blast.js example runs flawlessly on CodePen but encounters issues when run locally

I recently discovered blast.js and am encountering a problem when trying to run an example. The example functions perfectly on codepen, but fails to work on my local machine. The console is showing the following warning and error message. Any assistance fr ...

activating the submit button depending on the user input

My goal is to create a form with a textarea and a submit button that can be enabled or disabled based on whether there is any input in the textarea. I have confirmed that both the submit button and content are being selected correctly (I'll provide a ...

Loading an HTML page using jQuery's .load() method that contains embedded JavaScript

I'm facing an issue with loading .html pages (including JavaScript) into a div element. Below is my div setup: <div class="content"></div> This is my php code: <?php if(!$_POST['page']) die("0"); $page = (int)$_POST[&a ...

Incorporating Vuetify into a Vue CLI application with the help of webpack

I am facing an issue with my Vue CLI application that uses Webpack and Vuetify. The Vuetify components are not loading properly, and I keep getting the following warnings: Unknown custom element: < v-app > - did you register the component correctly? ...

Working on executing various methods with a JavaScript client on a Flask RESTful API that requires authentication

I'm currently developing a JavaScript client-side app to interact with a Flask RESTful API. I've implemented some methods that require user authentication, but for some reason, even after logging into the server, I receive a 401 error (Unauthoriz ...

Setting the height of a popper or div to '100%' in a React application with Material-UI

I'm having some trouble with my JSX code. <Popper id={id} open={open} anchorEl={anchorEl} style={{opacity:'0.5',width:'100%',size:'100%'}}> <div style={{backgroundColor: 'red'}}>The content of th ...

The Promise.all function encountered an error: Uncaught TypeError: #<Promise> is not an iterable object

Currently, I am dealing with the challenge of hitting two APIs and waiting for both responses to return before dispatching my action. Although I am utilizing Promise.all, I am encountering the following error: index.js:51 Uncaught (in promise) TypeErro ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...