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

What is the best way to modify and execute js and css (less) files dynamically using ajax and jQuery?

Whenever I click a button, an ajax call is triggered to load various html code into a div with the id 'main'. While displaying the html content is not an issue, integrating and applying css and js code to my current page has proven to be challeng ...

What is the best method for incorporating success icons into my website with vue.js?

Hey everyone, please excuse my lack of expertise as I am a beginner in this field. I'm trying to incorporate success icons into my website using bootstrap or similar tools, but I'm unsure of how to implement the if statement below. If anyone co ...

unexpected behavior when using jquery click function

I am currently working on a unique custom radio element that showcases images instead of the standard radio buttons. The basic HTML structure looks like this: <div id="wrap"> <p></p> <input type="radio" data-check='class-c ...

Continuous front-end promise awaiting response from back-end Node.js function

Currently, I am working on a basic React frontend where I need to fetch some data from my backend API powered by Node.js. This backend API calls an external API to get the required data. Although I have verified that the data is fetched successfully on the ...

When attempting to upload a file using Form, it only allows for a single upload of that file and will not work when attempting to upload the same file again

After selecting a file from the file chooser and uploading it, I encounter an issue when attempting to submit the form with the same file again. The submission doesn't seem to trigger any action. If I select a file, upload it, then choose the same fi ...

Transform the Nodejs server into a reusable Node module

Can a nodejs API server be transformed into a node module for use in other projects with minimal code modifications? Additional Information: The node js server contains various APIs (get, post, put). If I integrate this server as a node module within anot ...

Interactive Image Component in React

I'm encountering an issue with my React code. import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import RecipeService from "./RecipeService"; import RecipeProfileImg from "./Re ...

Expand the table in the initial state by using CSS to collapse the tree

I am struggling to collapse the tree view and need assistance. Below is the code snippet I've added. My goal is to have each node in the tree view initially collapsed and then expand a particular node on user interaction. For example, when I execute ...

"Need a hand with bookmarklets? Try using this code: document

Having an issue with my bookmarklet JavaScript where it always adds the www. portion to the domain. Any ideas on how to make it work by removing the www portion from the URL? Appreciate any help. javascript:void(window.open('http://siteanalytics.comp ...

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

Issue with Material UI components failing to return an HTMLElement reference

When working with certain libraries that require the ref prop to return an HTMLElement, I have noticed that 99% of MUI components do not fulfill this requirement. What am I missing? How can I obtain a reference to the root element of a component? import R ...

What is the purpose of the .Class method in ng.core.component within ES5?

ng.core.Component({ selector:'myapp', template:'<h1>Hello World</h1>' }). Class( { constructor:function() } ); ...

Troubleshooting problem with Angular UI-Grid cell templates

Currently, I am utilizing angular’s ui-grid feature which allows me to make the qty cell editable by double clicking on it. However, I need it to always be editable and display as an input type text. Although I have tried implementing this change, when ...

Emphasize specific lines within a textarea

I am facing a challenge with a textarea dedicated to validating telephone numbers. My goal is to highlight the lines that contain invalid telephone numbers by adding two asterisks in front of them. However, I'm struggling to figure out how to highlig ...

How can I implement the vm. syntax using ControllerAs in my application?

After reading various sources, including a few discussions on Stack Overflow, I have come to understand that the ControllerAs syntax is gaining popularity as it aligns with how things are done in Angular 2. Therefore, I decided to delve deeper into unders ...

What is the best way to execute fetch calls in sequence (A -> B -> C) within a React component?

I'm facing an issue with three fetch functions - a(), b(a_id), and c(b_id). The flow is such that function a returns an a_id which is then passed to function b, and b in turn returns an id passed to function c. componentDidUpdate(prevProps) { this ...

The HTML element failed to be inserted

Currently, I am involved in a project based on .NET Core for my organization. This project entails loading work orders from our SQL database using Entity Framework and then filtering them to display as markers on a map via the Google Maps API for our insta ...

What's the secret behind generating a crisp 400 on paper?

Understanding Why it Prints 400 I'm struggling to comprehend the logic behind this var x = {}, y = { key: "y" }, z = { key: "z" }; x[y] = 100; x[z] = 200; console.log(x[y] + x[z]); ...

Unable to assign an IP address to an Express JS application

Struggling to test a specific endpoint in Express, but consistently encountering a 404 error. var express = require("express") var app = express() //var http = require('http').Server(app) app.get('/', function(req,res){ res. ...