Creating a variable from a promise

I'm currently facing an issue where I am trying to assign a variable to one retrieved from a controller through a promise obtained from a factory. This factory fetches JSON data from a URL.

webApp = angular.module("App", []);

webApp.factory("getData", function($http) {
  var promise;
  var getData = {
    async: function() {
      if ( !promise ) {
        promise = $http.get(window.location+"/json").then(function (response) {
        return response.data;
        });
      }
      return promise;
    }
  };
  return getData;
});

webApp.controller("View", function(getData, $scope) {

  $scope.m = {}

  getData.async().then(function(m) {
    $scope.m = m;
    if ($scope.m == m) {
      console.log(true);
    }
  });

  console.log($scope.m);


});

Even though within the .then function true is returned, the value of $scope.m remains undefined.

If anyone has any insights or suggestions on how to resolve this, your input would be highly appreciated!

Answer №1

The reason behind this behavior is the asynchronous nature of promises. When you make an async call, it runs simultaneously with other parts of your code like the console.log() line. As a result, the variable may not be assigned at that particular moment.

Here is an example of how the output would appear:

app.controller("MainCtrl", function(getData, $scope) {
  $scope.data = {}

  getData.async().then(function(data) {
    $scope.data = data;
    console.log(data);
    console.log($scope.data);
  });
});

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

Opacity error with jQuery slider specifically affecting Google Chrome browser

My Magento site features a custom-built slider that is both responsive and has unique touch behavior. The desired behavior for the slider is as follows: A three-image slider where the middle image has an opacity of 1.0, while the other two images have an ...

ES6 Babel's grammar is set to be exported as the default

When using Babel, I am encountering an issue with importing the module shown below: // mongoose_helpers.js const r_string = { type: String, required: true } const r_number = { type: Number, required: true } export default { r_string, r_number } ...

When making a jQuery AJAX call, it redirects to the specified URL instead of staying on the current

In my Django project, I have a form structured as follows: <form class="myform" action="{% url "create" %}" method="post">{% csrf_token %} <div class="results"></div> <label class="input margin-bottom-10">{{form.name}} ...

Is there a way to deactivate the parent ng-click function?

My HTML code contains a structure with the ng-click attribute: <div ng-click="parent()"> <div ng-click="d"></div> </div> Is there a way to disable the outer ng-click="parent()" function when I click on ng-click="d"? ...

Utilizing the JQuery .not() method to fade out all div elements except for the one that is selected and its corresponding children

I have a grid consisting of images, each with a hover function that changes the opacity of a div. The image is set as a background image, while the information is placed within a div in each grid-item. <div class="grid"> <div class="grid-it ...

Filtering data based on button value with AngularJS click event

Is there a way to filter data based on a fixed button value in Angular JS? Specifically, I want to display only the data related to the "veg" category when the "veg" button is clicked. I am still new to learning Angular JS and could use some guidance with ...

Next JS is successfully importing external scripts, however, it is failing to run them as

In my upcoming project using the latest version 12.1.6, I am incorporating bootstrap for enhanced design elements. The bootstrap CSS and JS files have been included from a CDN in the pages/_app.js file as shown below: import '../styles/globals.css&apo ...

Query Mongo Db to locate and access a user's profile and retrieve comprehensive information on all their cards

Here is an example of a MongoDB User document: { "name":"steve", "email": "[email protected]", "password": "tnvddcnd", "cards": [{ "tags": "card", "user&qu ...

Using Django to Send a POST Request with JavaScript

I'm currently facing an issue with a JavaScript event-triggered function that is supposed to send a POST request to update objects in my database. The function is triggered by a drop-event, which made me initially avoid using forms for the request. Ho ...

"Can you explain the functioning of this Node.js middleware when it doesn't require any

Currently, I am utilizing a function created by another individual for express and passport, which defines the middleware in the following manner: function isLoggedIn(req, res, next) { if (req.isAuthenticated()){ return next(); } els ...

Tips for correctly cloning a create-react-app repository and compiling it (with existing error) - (Git)

After developing on a different server, I am now looking to move my project to the live server. On the live server, I initiated the create react app using: create-react-app test Then, I navigated into the project and initialized it with git: cd test gi ...

React Hooks: In useEffect(), unable to modify parent component's state

Within my component, I have a form for users to input a title, description, and images. This component is nested within its parent component, and I want the form data to be saved if the user switches sections and returns later without losing their progress ...

Creating a map with just a Button Click in React

I'm currently working on a weather app and making good progress. Now, I'm looking to display additional information when a button is clicked. I have a 5-day forecast and want to show the details for each day. I've managed to filter the data ...

Guide on leveraging event delegation to trigger a function depending on the id of the clicked element

Although I have experience with event delegation, I am currently facing a challenge in setting up a single event listener that can execute one of three functions based on the ID of the element clicked. Here is the existing code without event delegation: ...

An issue with the n constructor has been encountered for the bs4.5.2 dropdown in combination with jQuery version 3.5.1

When looking at index.html, I have these scripts included: <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protectio ...

What is the best way to reduce the size of images for uploading to a website

Our website, developed in .NET with a SQL Server database, functions as a marketplace where users can upload images and product descriptions. However, some customers encounter issues when trying to upload images, particularly when uploading multiple phot ...

Modify the appearance of a Javascript file that is parsing data from a text file

I am working on an HTML project where I have a JavaScript file that reads from a text file. Currently, the text from the file is displaying in my HTML file, but I would like to style it using CSS. Can anyone provide guidance on how to achieve this? I am st ...

What is the best way to insert HTML elements onto a webpage and retrieve them in an asp.net environment?

Greetings, For the past day, I've been attempting to dynamically add elements to a web page using Visual Studio and access their values. Either I'm overthinking things, being foolish, or there just isn't a straightforward way to achieve wha ...

Getting access to the parent's ref from child components in Vue/Nuxt can be achieved by using

Incorporating a global confirm modal component into my default layout file has been a challenge. Attempting to access this component from my pages/index.vue has proven to be unsuccessful, as calling this.$refs returns an empty object. While placing the mod ...

Tips for setting an identification value within mongodb?

Currently, my focus is on utilizing node.js and mongoose. I am in the process of developing a REST API to showcase my User model: var userSchema = new Schema({ _id: {type:Number}, username: {type:String}, age: {type:Number}, genre:{type: Number,ref:&a ...