Clarifying the confusion surrounding AngularJS $q, promises, and assignments

Curious about a particular behavior I'm witnessing. Unsure if there's a misunderstanding on my part regarding promises, JavaScript, or Angular. Here's what's happening (I've prepared a plnkr to demonstrate - http://plnkr.co/edit/ZKXkUv?p=preview):

<html ng-app="queue">
<head>
  <title>$q resolves for no one</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-resource.js"></script>
  <script>
    angular.module('queue', ['ngResource'])
      .controller('queueCtrl', ['$scope', '$q', function($scope, $q)
      {

        var _funk = true;
        $scope.testing2;

        var deferred = $q(function(resolve, reject)
        {
          if (_funk) {
            resolve({funk: 'yes'});
          } else {
            reject({funk: 'no'});
          }
        });

        deferred.then(function(resolved){
          console.log(resolved.funk)
        }, function(rejected){
          console.log(rejected);
        })

        function defReuse()
        {
          var toBeRet = {};
          deferred.then(function(resolved){
            console.log('yea')
            $scope.testing2 = resolved;
            angular.copy(resolved, toBeRet);
          }, function(rejected){
            toBeRet = rejected;
          })
          return toBeRet;
        }

        $scope.testing = defReuse();

      }]);
  </script>
</head>
<body ng-controller="queueCtrl">
  {{testing.funk}}
  {{testing2.funk}}
</body>
</html>

Attempting to extract a value from a promise object. Thought the most straightforward method would be by assigning it to something outside the promise object. In the plnkr, you'll notice that I can successfully retrieve the value either by assigning to a $scope variable or using angular.copy(). However, I seem to face challenges when trying to assign directly to the variable returned in the defReuse() function. Curious indeed, especially since I've declared the toBeRet variable in the global scope with no difference in outcome.

The question is why? Am I missing something crucial about the $scope variable, how Angular operates, or the mechanics of promises? It's a bit of a puzzle at the moment...

Answer №1

$q in Angular allows for asynchronous function execution, returning a promise that resolves and triggers the corresponding then method. To learn more about $q and promises in Angular, check out the following resources:

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

Sending a property as a parameter to a different component through Vue's router-link

I have a component designed to showcase recipes in a list format. Each recipe is rendered using a separate component from an array of recipes. I am currently attempting to pass the recipe object from one component to another component using Router-Link ...

Vue.js component mismatch in the layout

Attempting to set up a Vue application with vuetify while incorporating layouts. As a newcomer to Vue, I may have made some beginner errors. Here is the structure of my app: main.js // The Vue build version to load with the `import` command // (runtime- ...

What is the most foolproof method for detecting when a checkbox has been marked as checked, regardless of the circumstances?

Is there a way to detect changes in the checked value of a checkbox when it is changed by a script that I do not control? I have tried using `addEventListener()` and jQuery's `on()` method, but they do not work in all cases. <input type="checkbox" ...

Updating a table in Javascript after deleting a specific row

Is there a way to automatically reindex rows in a table after deleting a row? For example, if I delete row 1, can the remaining rows be reordered so that they are numbered sequentially? function reindexRows(tableID) { try { var t ...

Get an Array Using AJAX in PHP and JavaScript

Section 1 I want to retrieve an Array from PHP and use it in JavaScript. I have created a file using the fwrite function in PHP, then included that file in my next .load method inside a Div. The new PHP file contains an "include 'somefile.php';" ...

Discover the process of retrieving an image from the backend with React and Node.js

Hey there! I'm currently working on a Housing blog using ReactJS and NodeJS. One of the tasks I tackled was creating a login controller in NodeJS to send user details, including the image path from the database, to the frontend. The image path is sto ...

How to Extract a Link from JSON Data in React Native

My JSON data is formatted like this: orderData:"<p>Key VVV: 6326233</p> <p>Download link <a title=\"Movie\" href=\"https://play.google.com/store/movies/details/The_Angry_Birds_Movie_2?id=O_RbjOHHpIs&hl=en\" t ...

Converting a Class Component to a Functional Component in React: A Step-by-Step

I need to refactor this class-based component into a functional component class Main extends Components{ constructor(){ super() this.state = { posts:[ { id:"0", description:"abc", imageLink: ...

Getting the dimensions of an image using a path in JavaScript

I am trying to display a div with an image, its name, size, and download link using jQuery. Here is the code I have created: var image = 'image/example.png' $('#download').attr("href", result2); $('.image').attr("src", re ...

Replicate the function of the back button following the submission of an ajax-submitted form to Preview Form

I am currently working on a multi-part form with the following data flow: Complete the form, then SUBMIT (using ajax post) jQuery Form and CodeIgniter validation messages displayed if necessary Preview the submitted answers from the form Options: Canc ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

The query parameter is not defined in the router of my Next.js app API

I'm currently working on building an API endpoint for making DELETE requests to remove albums from a user's document in the MongoDB Atlas database. Struggling with an error that keeps popping up, indicating that the albumName property is undefin ...

PhantomJS Karma encountering SyntaxError when trying to export variables

I've encountered an issue while running Karma and PhantomJS. When I attempt to run, the console displays the following message: 22 03 2016 14:58:47.865:WARN [karma]: No captured browser, open http://localhost:9876/ 22 03 2016 14:58:47.875:INFO [karm ...

Issue arises when there are several inline <script> tags containing parameters which result in filtered JSON output

As a newcomer to JavaScript, I am faced with the challenge of creating a centralized glossary within a confined educational environment (LMS) that lacks a database or any other facilitating elements. My objective is to develop a script hosted on our applic ...

Error 404 in NodeJS: Page Not Found

I recently started working with NodeJS to develop an ecommerce application. I have a ready-made design and all the front-end components built using AngularJS code. Everything seems to work fine - when clicking on any menu, the page content changes along wi ...

Trouble with a basic Angular demonstration

After replicating an angular example from w3schools (found here), I encountered some issues with it not functioning correctly. Despite my efforts, the code appears to be accurate. Can anyone spot what might be going wrong? To provide more context, here is ...

Contrasting images showcasing Headless vs Non Headless settings in Puppeteer

I'm currently attempting to capture a screenshot or PDF of the content available at this URL. When using the option {headless: false}, the screenshot is generated correctly; however, in headless mode, some images do not render in the screenshot (for e ...

Activate validation when the scope of a custom validator is modified

Consider a scenario where we have a custom validator with an input as the attribute's value. app.directive('inputRequired', function() { return { require: 'ngModel', scope: { inputRequired: '=& ...