What is the best way to get $q.all to function properly in this scenario?

Having some trouble with my implementation of $q.all in the code snippet below. It seems I may have misunderstood a few concepts as it's not functioning as expected. Would greatly appreciate any guidance or tips.

The specific problem lies within $q.all(toSend.pie.slices).then():

var someData = {...};
var toSend = {
    pie: {
        slices: []
    }
};

toSend.pie.slices = generatePieSlice(someData);


$q.all(toSend.pie.slices).then(function(data){
    if(data) {      
        console.log(data);  // currently returning undefined :(        
        //perform additional actions
    }
});  



function generatePieSlice(data) {
    var arr = [];
    if(data) {
        angular.forEach(data, function(resp_o, resp_n){
            arr.push({
                name: resp_o.display,
                marketValue: resp_o.value,
                percentage: resp_o.percentage,
                key: resp_n
            });
        });
    }
    $q.all(arr).then(function(data) {
        if(data) {
            console.log(data); // correctly displaying the data
            return data;
        }
    });

}

Answer №1

Many thanks to the contributors for their assistance. Here is the final solution that I came up with for those who may find it helpful :)

const someData = {...};
const toSend = {
    pie: {
        slices: []
    }
};


$q.all({

    pieSlices: generatePieSlice(someData)

}).then(function(data){

    if(data) {      
        toSend = {
            pie: {
                slices: data.pieSlices
            }
        };

        // deferred.resolve(toSend) or alternative action :)
    }

});  


function generatePieSlice(response) {
    const arr = [];
    if(response) {
        angular.forEach(data, function(resp_o, resp_n){
            arr.push({
                name: resp_o.display,
                marketValue: resp_o.value,
                percentage: resp_o.percentage,
                key: resp_n
            });
        });
    }                
    return arr;
}

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

Tips for designing a Quasar page that dynamically loads content as the user scrolls

I am attempting to develop a component that will render multiple elements as the page is scrolled. I am utilizing the Quasar framework for Vue.js. Below is the code required to render a single block containing information from a JSON file: Quasar comes wi ...

What are some ways to accomplish this task without relying on a photo editing tool?

Is it possible to swap the image link: https://i.sstatic.net/Wa4mo.jpg with this new link: https://i.sstatic.net/hqVuQ.jpg without having to use a photo editor? Below is the CSS and HTML code: I was unable to upload the logo due to the restrictio ...

Display/Conceal/Inactivate form input and division

I am utilizing the code snippet below to display a div and disable certain input values based on selection changes. The choices are Approval, Request, and Change. I suspect there is an issue with the third set of form options in my code. How can I modify i ...

"Utilize JavaScript to assign array values to the main object for efficient data

I am looking to parse a modified JSON file to create separate objects for each team and player. I want each object to have a key for the team name and the player name. Using JavaScript, how can I achieve the following structure: [ { name: 'Dallas St ...

Get a specific value from a map using a regular expression as the key

Trying to extract a value from a map using a regular expression as the key: const nameMapping = new Map([ ['Name1', 'This is some name'], ['Name1_2', 'This is another name'], [/^[A]{1}[0]{2}/, 'Name from r ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...

Issues with $mdDialog controller functionality in AngularJS Material are only occurring on certain computers

Below is the code snippet for mdDialog: function selectAddress(addressType) { $mdDialog.show({ controller: function ($scope, $mdDialog) { var savm = $scope; savm.addressType = addressType; savm.close = $mdDialog.hide; savm.f ...

When using the updateMany function, only update the field if it already exists, without creating a new key

My goal within the $set operation is to update a field only if it already exists. While $cond seems to be on the right track, it has the drawback of always creating the field, which is not what I want. Filtering to retrieve only existing fields seems like ...

The primefaces codeMirror is failing to properly load its own CSS and JavaScript files

I am experiencing an issue with codeMirror from primeface-extension when trying to use it with SQL syntax. Upon loading the page that contains this component, I encounter a 404 error where the Css and javascript components cannot be found. Despite having ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

Creating an interactive accordion table using vue.js and the v-for directive in the main element

Looking for some help on implementing this feature using VUE: https://jsfiddle.net/jacekpr/roschwvL/5/ Currently, my progress is here: https://jsfiddle.net/jacekpr/8bhpqc5s/13/ However, I'm facing an issue with having multiple root elements in the ...

What could be the reason for the absence of definition for 'res'?

As I work on coding a bot using discord.js, I am facing an issue while trying to set up a system where the bot can send a message as long as it is not blacklisted. However, every time I attempt to run the function, I encounter this error message: Reference ...

I am experiencing an issue with the Search Filter where it is not successfully removing

My goal is to filter colors when a user searches for a color code. Currently, the search function displays the correct number of filtered items, but the color bubbles are not being removed as intended. I am working on removing the bubbles when a search is ...

Avoiding the hashtag symbol in a serialized string

I have a serialized string that I am sending to the server, structured like this: counter=1&Id=4&type=2332&amount=3232&gstIncluded=3232&paymentMethod=2&notes=2332#fdsf&docId=0&ref=3232&isEdit=true The issue I am encoun ...

Showcasing the template dynamically in Angular directive as the scope changes

Provided below is my custom directive: function ajaxMessageData() { var ajaxMessage = { link: link, restrict: "EA", template: "success", scope: { success: '=' } }; return ajaxMessa ...

Adjusting the location of circles generated by d3 using a time interval

As a newbie to d3 and JavaScript, I'm facing an error that is beyond my current knowledge. I have successfully generated 6 circles using a 2D array and implemented a function to increment their x and y positions by 1 in each call of a timer. However, ...

Stop a loop that includes an asynchronous AJAX function

Embarking on my Javascript journey as a beginner, I find myself facing the first of many questions ahead! Here is the task at hand: I have a directory filled with several .txt files named art1.txt, art2.txt, and so on (the total count may vary, which is ...

jQuery encountering TypeError while attempting to retrieve JSON data

Attempting to retrieve JSON data from the following URL using the provided code snippet: $.ajax({ type: "GET", url: "https://covid.ourworldindata.org/data/owid-covid-data.json/", success: function (data) { $("h5").e ...

Eliminate any duplicate objects using JavaScript

Is it possible to remove duplicated objects with the same id using methods other than lodash's _.uniqBy? The id value is always changing, so sometimes I need to remove the object with id:123, but other times it will be a different id. import _ from ...

The issue with calling Ajax on button click inside a div container is that the jQuery dialog box is

Here is the code for my custom dialog box: $("#manageGroupShow").dialog({resizable: false, draggable: false, position:['center',150], title: "Manage Group", width:"50%", modal: true, show: { effect:"drop", duration:1000, direction:"up" }, hide: ...