Set the variable after catching it

Within my AngularJS application, I am utilizing a $watchCollection function to call the getBalance(address) function within the listener.

$scope.$watchCollection('settings',
  function() {
    for (i = 0; i < $scope.settings['accounts'].length; i++) {
      var bal = $scope.getBalance($scope.settings['accounts'][i]);
      console.log(bal);
    }
  }
);

The implementation of the getBalance function is as follows:

$scope.getBalance = function(addr) {
  var balance;
  if ($scope.settings.contract !== null) {
    $scope.settings.contract.deployed().then(function(deployed) {
      return deployed.balanceOf(addr);
    }).then(function(res) {
       balance = res.toNumber();
       console.log(balance);
       return balance;
    }).catch(function(err) {
      console.log(err.message);
    });
  }
  return balance;
};

An issue arises where the balance variable is correctly printed in the 'then' method but returns undefined within $watchCollection.

This discrepancy may be due to JavaScript continuing execution without waiting for a result, leading to the variable being read as undefined. How can I modify these code snippets to ensure that the result is retrieved when ready and appended to $scope.balance?

Answer №1

It seems like you are attempting to convert asynchronous code into synchronous code, which is not feasible. The promise needs to be carried all the way through in both cases.

Instead of assigning balance to a variable and returning that variable, return the promise itself. Then, utilize then within your $watchCollection to retrieve the value.

$scope.$watchCollection('settings',
  function() {
    for (i = 0; i < $scope.settings['accounts'].length; i++) {
      $scope.getBalance($scope.settings['accounts'][i])
        .then(bal => console.log(bal));
    }
  }
);

$scope.getBalance = function(addr) {
  if ($scope.settings.contract !== null) {
    return $scope.settings.contract.deployed().then(function(deployed) {
      return deployed.balanceOf(addr);
    }).then(function(res) {
       balance = res.toNumber();
       console.log(balance);
       return balance;
    }).catch(function(err) {
      console.log(err.message);
    });
  }

  return Promise.resolve(null);
};

Keep in mind, when working with functions that return Promises, ensure that all paths return a Promise to avoid issues (hence the use of Promise.resolve(null)).

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

Load jQuery results when scrolling to the top of the window

I have a function that triggers when I click a button to fetch more data from my table. I'm attempting to make it work when the button reaches a certain distance from the top of the window, but I've been unable to achieve this so far... $(funct ...

What is the proper way to input a Response object retrieved from a fetch request?

I am currently handling parallel requests for multiple fetches and I would like to define results as an array of response objects instead of just a general array of type any. However, I am uncertain about how to accomplish this. I attempted to research "ho ...

"Utilizing Vue.js to dynamically fill input fields based on the selection of an element

As I am still new to learning Vue.js, I may not be using the correct terminology here. My current project involves a basic Vue application where I have implemented a simple search box functionality. The search box triggers an event (v-on:blur) when text i ...

Trouble with populating Ext.grid.Panel from ExtJS4 JSON data

Despite researching various posts on the topic, I am still facing issues. Even after attempting to create a Panel with minimal data, I cannot seem to make it work. This problem is really puzzling me. Below is the code snippet that I am currently working wi ...

Accepting PHP multidimensional array through ajax

My PHP code includes a script to open a database, fetch data, and encode it into JSON format. include_once($preUrl . "openDatabase.php"); $sql = 'SELECT * FROM dish'; $query = mysqli_query($con,$sql); $nRows = mysqli_num_rows($query); if($nRow ...

The CanJS model is unable to retrieve data from a .json file

Implementing MVC using AMD in canjs with requirejs has been my current focus. Here's a look at my domains.json file: [ "1":{"uid": "1","urls": "domain1.abc.com"}, "2":{"uid": "2","urls": "domain2.abc.com"}, "3":{"uid": "3","urls ...

Angular 9 is throwing an error that specifies that the options provided in the @ViewChild decorator must be in

After successfully upgrading my Angular project from version 8 to 9, I encountered an error when trying to run the project on localhost or build it. The error message states: ERROR in @ViewChild options must be an object literal The @ViewChild syntax that ...

Display numbers greater than zero using Angular

If the price of a car is 0, I only want to display the name and leave the price blank. If the price is greater than 0, then both the name and price should be shown. Any suggestions on how to achieve this? <tr> <td>{{cars.name}}</td> & ...

Information is not transferring to Bootstrap modal

I attempted to send a value to a modal by following the instructions on the Bootstrap documentation here. However, I am facing an issue where the data is not being successfully passed. To trigger the modal, use the following button: <button type=" ...

Executing functions across modules in node.js

I need assistance with two of my modules: var client = require('./handlers/client.js'); var server = require('./handlers/server.js'); server.createClient() The client module: var client = function(){ console.log("New client"); ...

How to retrieve the present value from an array using AngularJS

Struggling to assign the current user from my list Here is my array after submitting the form [{"name":"Erich","surname":"Josh","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096c67497a7a276a6664">[email prot ...

Changing the display of elements using Javascript in IE6 by modifying class

Currently, I am facing an issue at work that involves a piece of code. The code functions correctly in Firefox 3.6 where clicking on a row changes its class name and should also change the properties of the child elements. However, in IE6 and possibly othe ...

What is the process for updating selenium-webdriver if it is not globally installed on my system?

After installing selenium-webdriver with the command npm install selenium-webdriver (without the -g option), I found that the usual instruction of running webdriver-manager update did not work since it was installed locally. What is the correct way to upd ...

What methods can be used to troubleshoot an issue of an AngularJS function not being called

I am facing an issue with a dynamic table I have created. The rows and action buttons are generated dynamically when the user clicks on the Devices accordion. However, there seems to be a problem with the function expandCollapseCurrent(). Whenever the use ...

Retrieving complete credit card information with the help of JavaScript

I've been grappling with extracting credit card data from a Desko Keyboard, and while I managed to do so, the challenge lies in the fact that each time I swipe, the card data comes in a different pattern. Here is my JavaScript code: var fs = require ...

changing the RadioButtonList to preselect a default value

On a page, I have a pre-existing RadioButtonList where I want to make the second button checked by default instead of the first one. Since I am unable to edit the original control directly, it seems like I might need to achieve this using javascript on th ...

Using JQuery to create animations with fadeIn and fadeOut effects is a great way to

As a complete newbie taking my first steps in front-end development, I spent most of my day trying to work out an animation function but couldn't quite get it right. Below are the snippets of HTML, CSS, and JavaScript codes: <!DOCTYPE html> < ...

Drop down menus fail to appear after the screen has been resized

Creating responsive menus involves using ordered and unordered lists, along with CSS for styling. I have added a script to dynamically generate dropdown menus, but encountered an issue where nothing appears on the screen upon resizing - only the backgrou ...

Maintain an equal distance between 2 out of 3 elements while resizing the window to ensure responsiveness

There are two image divs stacked on top of each other, positioned beside a fluid header logo (.svg) also contained in a div. The HTML: <header class="site-header" role="banner" itemscope="itemscope" itemtype="http://schema.org/WPHeader"><div cla ...

Develop a table with dynamic features in Angular according to the number of rows selected from a dropdown menu

I am currently exploring AngularJS 1.6 and tackling the challenge of dynamically populating a table with rows based on the number selected in a dropdown list, ranging from 1 to 12. Here's the code I have up until now: <body ng-controller="myContr ...