Obtaining information from AngularJS callback function in loopback: A comprehensive guide

I am trying to figure out how to retrieve the "good" array from an angular function. Here is the function I have in my Angular code:

app.run(function($rootScope,Communications,$http,$filter) {

    $rootScope.getCommunication = 
    function(object_type,val,id,isType,isSendSms,getNotes){

      var array = {};
      var newArr = [];

      // getting data from mysql data 
      var myVals = Communications.find({
            filter: {
              where: {
                and : [{
                  communications_type_code : val
                },{
                  object_id : id
                },{
                  object_type : object_type
                }]
              }
            } 
          }).$promise
            .then(function(data) {

              for(var ind=0; ind<data.length; ind++){
                array['address_type'] = data[ind].address_type;
                array['contact_value'] = data[ind].contact_value;
                array['send_sms'] = data[ind].send_sms;
              }

              newArr.push(array);
               return newArr;
            });
      return newArr;
    };
  });
  

When I try to call the function in my Angular controller like this:

var arr = $rootScope.getCommunication(2,3,$id);
  console.log(arr);
  

I see something like this in the console:

https://i.sstatic.net/qmIVV.jpg

But when I try to access arr[0], I get undefined. How can I access this data properly?

Answer №1

To ensure the proper execution of your code, it is important to return the promise instead of the array before it is updated. Asynchronous operations work by executing all synchronous code first before moving on to anything async.

var arr = []; // initialized first
promise.then(function(result){arr = result}) // executed third
return arr; // returned second 

It is crucial to modify your code to return the promise. However, this also implies that your calling code must be able to handle asynchronous operations.

function asyncFunc() {
 return promise.then(function(result){return result});
}

asyncFunc().then(function(result) {console.log(result)}) // prints the value of result.

In relation to the provided code snippet above:

app.run(function($rootScope,Communications,$http,$filter) {

$rootScope.getCommunication = 
function(object_type,val,id,isType,isSendSms,getNotes){
  // retrieving data from a MySQL database
  return Communications.find({
        filter: {
          where: {
            and : [{
              communications_type_code : val
            },{
              object_id : id
            },{
              object_type : object_type
            }]
          }
        } 
      }).$promise
        .then(function(data) {
          var array = {};
          var newArray = [];
          for(var ind=0; ind<data.length; ind++){
            array['address_type'] = data[ind].address_type;
            array['contact_value'] = data[ind].contact_value;
            array['send_sms'] = data[ind].send_sms;
          }

          newArr.push(array);
           return newArr;
        });
};
});

and the corresponding function call:

var arr = $rootScope.getCommunication(2,3,$id)
                    .then(function(arr){console.log(arr)})

Answer №2

If you want to utilize callback functions, you can do so by following this method:

app.run(function($rootScope,Communications,$http,$filter) {

$rootScope.getCommunication = 
function(object_type,val,id,isType,isSendSms,getNotes, callback){

  var array = {};
  var newArr = [];

  // Fetching data from MySQL database
  var myVals = Communications.find({
        filter: {
          where: {
            and : [{
              communications_type_code : val
            },{
              object_id : id
            },{
              object_type : object_type
            }]
          }
        } 
      }).$promise
        .then(function(data) {

          for(var ind=0; ind<data.length; ind++){
            array['address_type'] = data[ind].address_type;
            array['contact_value'] = data[ind].contact_value;
            array['send_sms'] = data[ind].send_sms;
          }

          newArr.push(array);

           // Returning data using callback
           return callback(newArr);

        });

  // Returning data using callback
  return callback(newArr);

};
});

You can access the result by using the callback function like this:

$rootScope.getCommunication(2,3,$id, function(result){
  var arr = result
})

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

What is the best way to implement lazy loading of images that have not been downloaded in a JavaFX WebView?

Currently, I am in the process of developing an email client application using JavaFX WebView to showcase email HTML files. In order to enhance its responsiveness and speed, my goal is to display inline images in emails as they are downloaded locally. Duri ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...

Retrieving input values from forms

angular.module('app', []) .controller('mainCtrl', ['$scope', function ($scope) { $scope.checkVal = function () { console.log('entered'); console.log($scope.data.user) } ...

Why is there nothing showing up on the screen?

Just diving into Three.js and might've messed up somewhere. I'm trying to generate a geometry by using coordinates and surface data from a .k file. I checked the geometry.vertices and geometry.faces, they seem fine. I even played around with the ...

Reiterate list of inquiries using InquirerJS

How can the questions be reset or have a specific answer lead to another previous question? var questions = [{ { name: 'morefood', message: 'Do you want more food?', ...

What is the process for importing Buffer into a Quasar app that is using Vite as the build tool

I'm having issues with integrating the eth-crypto module into my Quasar app that utilizes Vite. The errors I'm encountering are related to the absence of the Buffer object, which is expected since it's typically found in the front end. Is ...

Implementing a Button Click Event Listener on a Separate Component in React

Currently, my React application incorporates MapBox in which the navbar is its parent component. Within the navbar component, there is a button that collapses the navbar when clicked by changing its CSS class. I also want to trigger the following code snip ...

Is the z-index useless when the button is positioned behind divs and other elements?

I would like the "Kontakt" button to appear in the top right corner of the page, always on top of everything else. I have tried setting the z-index to z-index: 99999999999 !important;, but it doesn't seem to be working... On desktop, the button displ ...

What is the best MySQL data type for storing JavaScript code with PHP?

I am creating a platform that resembles jsfiddle, allowing users to store their JavaScript codes and retrieve them in an organized manner. I am unsure about which data type would be most suitable for saving the codes, or if storing them in text files wou ...

Removing an object from an array when a certain key value already exists in TypeScript

I'm currently facing an issue with my function that adds objects to an array. The problem arises when a key value already exists in the array - it still gets added again, but I want it to only add if it doesn't exist yet. Here's what I have: ...

Utilizing JMeter's WebDriver Sampler to Upload Firefox Profile

Currently, I am working on creating a JMeter script to measure the UI response time for different events using the WebDriver Sampler plugin. In my application, access to the GUI is restricted to certificate-authentication only. Therefore, my concern is wh ...

Issue: [$injector:unpr] Provider not found: RequestsServiceProvider <- RequestsServiceFor more information on this error, please visit the website: http://errors.angularjs.org

Despite defining my service name in all necessary places, I am still encountering the error mentioned above. Below is my app.js: var app = angular.module('ionicApp', [ 'ionic', 'ngCordova', 'checklist-model' ]) ...

Tips for sending data through AJAX before the browser is about to close

My issue is with a javascript function that I've called on the html unload event. It seems to be working fine in Google Chrome, but for some reason it's not functioning properly in Firefox and IE. <script> function fun() { ...

What is the process for refreshing HTML elements that have been generated using information from a CSV document?

My elements are dynamically generated from a live CSV file that updates every 1 minute. I'm aiming to manage these elements in the following way: Remove items no longer present in the CSV file Add new items that have appeared in the CSV file Maintai ...

Table Header Stays Put Without Shrinking or Expanding with Window Adjustment

I have a sticky table header that stays at the top when scrolling down on my web page. To achieve this effect, I followed the solution provided on css-tricks.com/persistent-headers/. However, I encountered an issue where the sticky table header does not ...

jQuery not functioning properly when attempting to add values from two input boxes within multiple input fields

I am facing an issue with a form on my website that contains input fields as shown below. I am trying to add two input boxes to calculate the values of the third input box, but it is only working correctly for the first set and not for the rest. How can ...

Load images sequentially in a slideshow gallery using JQuery, showing the next five pictures at a time instead of loading all at once

Recently, I've been developing a slideshow for educational materials and images. However, a concern was raised by a colleague regarding the loading time of slideshows with over 50 images. Is there a way to optimize the loading process by only displayi ...

Encode JavaScript field without affecting the appearance

I need to encode a specific search field before submitting it as a $_GET request. To do this, I am using the encodeURIComponent() function on that field before the form is submitted. $('#frmMainSearch').submit(function() { var field = $(this ...

The function this.listCatModel.push is not a valid operation

I have a dropdown that I want to populate using the following code: this.categoryService.GetListItem(this.GetAllcatListUrl).subscribe(data=>{ this.listCatModel=data, this.listCatModel.push({ id:0, name:'Main Category', parent ...

How to retrieve all the text inside an element using Protractor and Selenium

<div class="test"> <span> <div>CONTENT </div> </span> <div> <ul> <li> <span>More text</span> EXAMPLE1</li> <li>EXAMPLE2</li> ...