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

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

Instantly refreshing the Angular DOM following data modifications and retrieval from the database

I am currently working on a Single Page Application that uses Angular 8 for the frontend and Laravel for the backend. This application is a CRUD (Create, Read, Update, Delete) system. The delete functionality is working as expected, deleting users with spe ...

The Angular UI tree is malfunctioning on Mozilla Firefox

Check out this Plunker example. While this Plunker works well in Chrome and IE, it encounters issues in Mozilla Firefox. There seems to be a problem with the dropdown selection causing the page to reload. Any ideas on how to fix this? <script type= ...

Best practices for implementing JavaScript in JSP pages

After researching various sources, I have come across conflicting opinions on the topic which has left me feeling a bit confused. As someone new to web programming using java EE, I am looking to integrate javascript functions into my code. It appears that ...

Understanding JavaScript JSON Object Parsing

$(document).ready(function () { var oOpenOrders = new Array(); $('#btn').click(function () { $.ajax({ type: 'GET', url: 'http://192.168.19.22/test.php', contentType: "applica ...

What is the process to include an image file in a JSON object using PhoneGap?

Having trouble saving an image in JSON. Managed to access the mobile camera with the provided code: var pictureSource; // source of the picture var destinationType; // sets the format of returned value // Wait for PhoneGap to connect with the device / ...

Deciphering JSON information extracted from a document

I am currently working on a Node JS project where I need to read a file containing an array of JSON objects and display it in a table. My goal is to parse the JSON data from the array. Below is a sample of the JSON data: [{"name":"Ken", "Age":"25"},{"name" ...

What are the steps to ensure that this iframe adjusts perfectly to the page in terms of both vertical and horizontal dimensions

I have a sandbox from Material UI that you can view at this link: https://codesandbox.io/s/material-demo-forked-c8e39?file=/demo.js Upon loading the page, an iframe displays some HTML content. Although the width fits perfectly, there are two vertical scro ...

``"Selecting a location upon clicking a marker in the array

I have limited experience with javascript but I am determined to improve my skills. Currently, I am facing a major roadblock in a project that I am working on and urgently require assistance. The project involves creating a map with marked locations from ...

Issue with TinyMCE Editor: Inoperative

<script type="text/javascript" src="<your installation path>/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", theme: "modern", plugins: [ "advlist autolink li ...

Issues arise with req.body being undefined when using node.js in conjunction with Express version 4.16.X and Body-Parser version

Recently, I began using node.js to construct a RESTFul API. Currently, my focus lies in inserting data through POST requests with JSON in the body. However, I encountered an issue where the req.body always returned as undefined. Upon investigating further ...

Are there any debugging tools specific to Internet Explorer for JavaScript?

I need a reliable JavaScript debugger for Internet Explorer. I have tried using Firebug Lite, but it doesn't seem as detailed as the original Firebug when it comes to displaying JavaScript errors. Does anyone know how to pinpoint JavaScript errors in ...

Displaying content based on changing conditions fetched from the database

We are currently developing a dynamic form system where users can create custom questions in the admin panel and set conditions to display them based on the values of other questions. ng-show="((UserCode==10003 && Name=='Ankur') ||(State ...

Leveraging the power of ajax to securely save information in a database with the web2py framework

Struggling with a major issue here. I have set up the following tables db.define_table('post', Field('user_email', default=auth.user.email if auth.user_id else None), Field('title', 'strin ...

Is it possible for PHP to delay its response to an ajax request for an extended period of time?

Creating a chat website where JavaScript communicates with PHP via AJAX, and the PHP waits for the database to update based on user input before responding back sounds like an intriguing project. By using a recall function in AJAX, users can communicate ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

Generate text in a random spot effortlessly

After doing some research on various development platforms, I stumbled upon this JSFiddle that seems to have a solution for my requirements. The only thing missing is the ability to input a specific word (without user input) and automate the process at fix ...

Efficient methods for transferring information between a main and pop-up page within angularjs

On my webpage, I have a button that opens a popup page. I need to figure out a way to transfer json data from the main page to the popup page. These two pages are running separate angular applications. Once the data is transferred, it will be updated base ...

What is the hexadecimal color code for a specific element's background?

How can I retrieve the background color code of a specified element? var backgroundColor = $(".element").css("background-color"); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="elemen ...

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...