Generating varying commitments from one function

I have encountered an issue where I am returning a promise from a function that is part of a $q.all array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to update the view with new data.

Here is the working code:

var vm = this;
var loadingGames = $q.defer();
var loadingPlayers = $q.defer();

var getGames = function() {
  playersService.getGames({
    playerId: playerId
  }).$promise.then(function(data) {
    vm.games = data;
    loadingGames.resolve();
  });
};

var getPlayers = function() {
  playersService.getPlayers({
    playerId: playerId
  }).$promise.then(function(data) {
    vm.players = data;
    loadingPlayers.resolve();
  });
};

$q.all([loadingGames.promise, loadingPlayers.promise]).then(function() {
  populateOptions(vm.games);
  vm.tableParams.reload();
});

var init = function() {
  getGames();
  getPlayers();
}

init();

The problem here is evident: loadingGames was already resolved on page load, so depending on it will not fetch any updated data:

var updateStatus = function() {
  getGames();
  loadingGames.promise.then(function() {
    populateOptions(vm.games);
    vm.tableParams.reload();
  });
};

I attempted another approach by modifying the code as follows, but faced an error "

TypeError: Cannot read property 'then' of undefined
" while trying to execute updateStatus:

var updateStatus = function() {
  getGames().then(function() {
    populateOptions(vm.games);
    vm.tableParams.reload();
  });
};

How can I ensure that future promises for getGames() are resolved correctly so that updateStatus() receives updated data?

Update: I made another attempt using a callback, but unfortunately, the functions within the callback were never executed.

var updateStatus = function() {
  getGames(function() {
    populateOptions(vm.games);
    vm.tableParams.reload();
  });
};

Answer №1

To achieve the desired outcome, it is essential to include $q.defer() in your function and ensure that you return a promise. By following this approach, combining these promises becomes a seamless task.

The included example showcases the implementation with both a Service and Controller:

Service

(function(){

  function Service($q){

    var games = ['zelda', 'mario'];

    var players = ['john', 'Donkey kong'];

    function getGames(){
      return $q(function(resolve){
        resolve(games);
      });
    }

    function getPlayers(){
      return $q(function(resolve){
        resolve(players);
      });
    }

    function addGames(name){
      games.push(name);
    }

    function addPlayers(name){
      players.push(name);
    }

    return {
      getGames: getGames,
      getPlayers: getPlayers,
      addGames: addGames,
      addPlayers: addPlayers
    }

  }

  angular
    .module('app')
    .factory('Service', Service);

})();

Controller

(function(){

function Controller($scope, $q, Service) {

  var vm = this;

  var getGames = function(){

    var defer = $q.defer();

    Service.getGames().then(function(response){
      defer.resolve(response);
    });

    return defer.promise;

  }

  var getPlayers = function(){

    var defer = $q.defer();

    Service.getPlayers().then(function(response){
      defer.resolve(response);
    });

    return defer.promise;

  }

  var updateStatus = function() {
    
    Service.addGames('Skyrim');

    getGames().then(function(response){
      
      console.log('Data updated !');
      console.log(response);
    });
  };

  var promise1 = Service.getGames();
  var promise2 = Service.getPlayers();

  $q.all([promise1, promise2]).then(function(response){
    var games = response[0];
    var players = response[1];
    console.log('first');
    console.log(games);
    updateStatus();
  });



}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

By implementing the changes suggested, both getGames() and getPlayers() functions will now return a promise.

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

Responsive div that reacts to scrolling

I am looking for a div that can dynamically change its position as I scroll up or down the page. For example, it could start 30px from the top but then move to 100px as I scroll down further. This div will be located on the right-hand side of my page, clo ...

Error in Angular Due to Circular Reference in JSON

I'm currently working on integrating a tree structure in AngularJS. The goal is to construct the tree by dynamically adding nodes based on user input from an Angular Select element. Here is the specific operation I'm trying to accomplish: var a ...

How to prevent the parent element from scrolling when changing the value of a number input by scrolling

Within a container with fixed dimensions and scroll bars that appear when the content size exceeds the container, there is a form. This form contains an input of type "number" which allows changing its value using the mouse wheel. The issue arises when at ...

The concept of nesting templates in Angular

I'm encountering an issue with my directive that has an item template recursively referencing itself, but it's not rendering out children beyond the first level. Despite checking various examples, the only difference I can spot is that my items a ...

What could be causing the createReadStream function to send a corrupted file?

My current task involves generating a file from a URL using the fs module to my local system. Initially, everything seems successful. However, when attempting to post this file into a group using the createReadStream() function, I encounter an issue where ...

The problem of interpreting JSON using the JavaScript eval() function

Here is the JSON string provided : { "name":"Ruby on Rails Baseball Jersey", "price":"19.99", "id":"1025786064", "image":"" }, { "name":"Ruby on Rails Baseball Jersey", "price":"19.99", "id":"1025786064", "image":"" }, { "name ...

Eliminate repeated elements within a JSON dataset to create a consolidated array

Looking to extract unique data from the JSON object below in order to create a result json with a list of questions and their corresponding choices. Any assistance would be greatly appreciated. Thanks in advance..!! var data = [ { "category": "s ...

Using a JSON web token (JWT) for authorization on a json-server

I am currently working on developing a Node.js application that utilizes typicode json-server. My goal is to implement authorization within the app, where all public users have access to GET requests, but PUT, POST, and DELETE requests require a JWT token ...

JavaScript Object Featuring a Default Function Along with Additional Functions

I'm currently working on developing a custom plugin, but I've hit a roadblock at the initial stage. My goal is to create an object that can accept a parameter as its default and also include other functions within it. Below is an example of what ...

Discovering additional element information while utilizing the 'Sortable' feature

My Current Objective: In my setup, I have a 'calendar' comprising 5 columns, each column containing 5 separate divs known as timeslots. The main purpose here is to show appointments in these specific timeslots and utilize JQuery's Sortable ...

dynamic rendering in React based on the value passed through props

I am attempting to render a component using react.lazy, where the path is a variable in my props. However, I am encountering an error with webpack. The parent component sends the props like this: <DynamicModal url = 'Impuesto/formulario&apo ...

Choose the option using Angular and .NET Core

I am facing an issue with my Angular controller that handles GET and POST requests for data. I had two controllers working properly, but when I added a third one by combining the previous two, the GET and POST functionalities stopped working. Can someone h ...

Separating a variable within a Twitch bot: techniques and tips

I am working on setting up a feature in my Twitch bot where it can respond to the command !test [var]. For example, if someone types !test @jeff, the bot would reply with hello @jeff. Currently, I am using tmi. client.on('chat', function(channe ...

Fetching information from WebMethod with Jquery Ajax in c#

I have a jQuery variable that contains the following values: var data = [['Vikas', 75], ['Sumit', 55], ['Rakesh', 96], ['Shivam', 123], ['Kapil', 34], ['Rana', 104]]; Now, according to my requir ...

What is the best way to choose the current Div's ID, as well as its Width and Height properties?

Within this section, there are four div elements with varying widths, heights, and colors that appear and disappear when their respective buttons are clicked. I am adding an "activeDiv" class to the visible div in order to easily select it using that class ...

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

Exploring the Differences Between Arrays in JavaScript

I am currently tackling the task of comparing arrays in JavaScript, specifically within node.js. Here are the two arrays I am working with: Array 1: [16,31,34,22,64,57,24,74,7,39,72,6,42,41,40,30,10,55,23,32,11,37,4,3,2,52,1,17,50,56,60,65,48,43,58,28,3 ...

How to eliminate the unnecessary gap between rows in a Vue div displayed as a grid

I have recently started working with Vue and in my current project, I encountered a challenge where I needed to display 2 players in each row within a div. To achieve this, I utilized the display: grid; CSS property on the playerDiv id. However, I am facin ...

When the add button is clicked, I would like to implement a feature where a checkbox is added

When the user clicks on the link "출력하기", I want the web page to add a checkbox to all images. I wrote this code, but it's not working. Can anyone help me? This is my JS: $(document).ready(function(){ $("#print").on('click', fu ...

Using JavaScript, concatenate text from each line using a specified delimiter, then add this new text to an unordered list element

I am looking to extract text from named spans in an unordered list, combine them with a '|' separating each word within the same line, and append them to another ul. Although my code successfully joins all the words together, I'm struggling ...