Delay the completion of an Angular Factory Resource Call within a for loop

Hey there! I've been experimenting with the promise technique to wait for calls inside a for loop, but I'm having trouble making it work.

When I try "return mainArr," it returns undefined.

//export CSV

Looping Through Data

//Assumes that data is a list of JSON objects

function getCustomData(data){

            var mainArr=[];
            for (var i = 0; i < data.length; i++) {
                var obj={};
                obj.word = $('#type-ahead-input').val();
                obj.synonym = data[i].word;
                obj.similarityCount = (data[i].similarityCount).toFixed(2);
                obj.emailCount = data[i].occuranceCount;
                obj.synonymlist = getSynonymList(data[i].word);
                mainArr.push(obj);

            }
            return mainArr;
        }
        function getSynonymList(inputWord){
            return WordService.getSynonymList({
                ids : inputWord
            }).$promise
                    .then(function($response) {
                        var output = $response;

                        var wordList =[];
                        for (var i = 0; i < output.length; i++) {
                            wordList.push(output[i].word);
                        }

                        return wordList;
                    });
        }

Factory Resource Call Signature

getSynonymList : {

        method : 'GET',
        isArray: true,
        async  : false,
        url : appRoot + '/synonym',
        params : {
            word : '@word'
        }
    },

Answer №1

To handle multiple promises, you should push the values into an array and then use $q.all() for resolution.

function fetchUserData(data){

        var promiseArr = []; // create an array to store promises
        for (var i = 0; i < data.length; i++) {
             // include your code here

            var newPromise = $q.when(data);  // generate a promise             
            promiseArr.push(obj);
        }

        return $q.all(promiseArr);
    }

You can access the returned values using callback functions

myService.fetchUserData(data).then(
  function successHandler(returnData){
    console.log(returnData);
  }, 
  function errorHandler(error){
    console.log(errorMessage);
}

This methodology is applicable to all your functions that involve loops. (Note that this is a suggested outline and has not been fully implemented)

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

A guide to incorporating Vue multiselect in a vanilla JavaScript file without using the Command Line Interface (

I am trying to incorporate vue multiselect into my Vue app that I created without using the cli. My app is built with plain JS and all the content is within my HTML file. However, I am having trouble importing libraries such as Vue Multiselect :( In HTML: ...

"Jesting with JavaScript: Thou shall be warned, for undefined does

While running my unit tests with jest, I encountered an error: TypeError: Cannot read properties of undefined (reading 'getVideoTracks') Can anyone provide suggestions on how to properly test the following line using jest? [videoTrack] = (await ...

Sending data from a JavaScript variable to PHP within the same page

I've been attempting to transfer a JavaScript variable to PHP within the same page without success. I have tried different codes but none seem to be working as expected. Here is the current code snippet: function init(e){ $('#DeleteDaily' ...

Converting TypeName from VBScript to JavaScript

Can anyone assist me with converting the following VBScript code to JavaScript? If TypeName(document.all(cFieldName)) = "HTMLInputElement" Then ElseIf TypeName(document.all(cFieldName)) = "HTMLSelectElement" Then I attempted using if(typeof $("#" + (cFie ...

No tests were located for execution. Despite our efforts, a cypress.json file was not found in the search

Having recently set up Cypress in my project, I encountered an issue while attempting to run it using npx cypress run. The error message displayed was: Could not find any tests to run. We searched for a cypress.json file in this directory but did not ...

The PHP Ajax code runs a for loop twice, but the data is only stored once during its execution

<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body onload="searchVideo();"> <script> var data_length = 2; for(var i=0; i<data_length; i+ ...

Threejs collada loader tutorial: converting a scene into an object3d

Currently working on an augmented reality project and I'd like to incorporate an Object3D into another object for rendering purposes. Using the ColladaLoader to bring in the object, but the output is a Scene which doesn't quite fit my requiremen ...

The value retrieved from the event handler function's state does not match the anticipated value

While debugging, I often minimize this particular component to understand its behavior later on. It was quite challenging to pinpoint the issue due to some intricate logic in place. Nonetheless: import { useContext, useEffect, useState } from "react&q ...

Exiting a NodeJs function entirely rather than just returning from an internal function

There is a function in my code app.post('/assignment/loan', (req, res) => { Within that function, there is another function db.run('SELECT loanable FROM book WHERE id=?',[bookID],(err,row)=>{ I tried using return but it only exi ...

Is there a way to update a useState in TabPanel without causing a re-render?

For the past few months, I've been immersing myself in React and MUI. Recently, I encountered a problem that has me stumped. The Goal: I receive data from a backend and need to display it for users to edit before sending the changes back to the serv ...

Learn the process of incorporating meta-data into an express route and retrieving it efficiently with the help of router.stack

I'm working with a set of routes that are defined in a routes.js file like this: const express = require('express'); const router = express.Router(); const controller = require('../controllers/mycontroller'); router.get('/&ap ...

"Double trouble: why are my events firing twice in jqWidgets

Why does this event trigger twice? Even after implementing a workaround to check for event arguments, the event continues to fire twice. $('#input').jqxInput({ width: 200, height: 25 }); var changedCount = 0; $('#input' ...

Is there a way for me to determine the value of this variable using the Firefox debugger tool?

Recently, I've started delving into the world of debugging JavaScript and AngularJS. Despite having breakpoints set up at almost every line in the code snippet below, I can't seem to locate the response variable or the values for data and content ...

Received an error message when attempting to use the Discord mute command: TypeError - function is not recognized

I encountered an error that I need help with: C:\Users\(private)\discord\bots\(private)\node_modules\@discordjs\collection\dist\index.js:161 if (fn(val, key, this)) ^ TypeError: ...

The useState hook in Next.js with Typescript is not supported

I'm working on adding a filter to my movie list. My plan is to store all the movies in 'default' and then apply filters from there when needed. However, I encountered an error along the way: Here's a snippet of my code: const [movies, ...

Is placing JavaScript on the lowest layer the best approach?

I'm facing a unique situation that I haven't encountered before and am unsure of how to address it. My website has a fixed top header and footer. On the left side, there is a Google Adsense ad in JavaScript. When scrolling down, the top header s ...

Unlock the full potential of knockout.js by mastering how to leverage templates recursively

Given the following model and view model for nested categories: function Category(id, name) { var self = this; self.Id = ko.observable(id || '00000000-0000-0000-0000-000000000000'); self.Name = ko.observable(name); self.children ...

What causes the "undefined" error in Node.js when using a

Currently, I am utilizing the node-craigslist package for scraping listings from craigslist. However, I have encountered an issue when processing the results. client .search(options, '') .then((listings) => { listings.forEach((listing ...

Unable to retrieve scope data in controller function

Having trouble accessing the scope attribute fullName from the controller method login. What could be causing this issue? App.controller('LoginController', ['$scope', 'LoginService', '$location', function(scope, Log ...

Enhancing website functionality with Regex in Javascript

So, here is the code I am working with: var patt = new RegExp("/.+/g"); var device_id = patt.exec("javascript:project_id:256, device_id:2232"); Surprisingly, after running the above code, the value of device_id is empty and I can't seem to figure ou ...