What is the best way to handle resolving a promise nested within another promise and retrieving the result within a controller?

I have a situation where I need to modify the result of a promise returned by a function in one service and make this altered value accessible to my controllers from another service.

angular.module('test').service("service1", function($q) {
      function doSomething(something) {    
           //parses some data
           return deferred.promise;
       }

  return {
      doSomething: doSomething
  }
 });

 angular.module('test').service("service2", ['service1', $q, function(service1, $q) {
     var deferred = $q.defer();
     var myResult = deferred.promise;      

     service1.doSomething("test").then(function (result) {
         var alteredResult = result + "Altered"; //result I want to be accessible by my controllers
         deferred.resolve(alteredResult)
     });

 return {
      myResult: myResult
  }
}]);


angular.module('test').controller('testController', ['$scope', 'service2', function ($scope, service2) {

      $scope.test = service2.myResult;

}]);

I encountered an issue when trying to initialize and update myResult as it was passed to the controller before being altered. This led me to explore creating another promise within service2.

However, the result in $scope.test ended up being an empty {} javascript object.

How can I correctly store the modified result of service2 for access by controllers?

Thank you for your time. Please let me know if you require more information or if I am unclear.

Answer №1

It is recommended to handle promises correctly by resolving them and then assigning the resolved value to the scope variable.

service2.myResult.then(function(result) {
  $scope.test = 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

Executing function with ng-click in AngularJS only on the second click of the button

Currently, I am studying AngularJS and working on an exercise that involves using the ng-click function. Strangely, I am only able to view the result after clicking upload for the second time. I am trying to display my json content but it's not workin ...

Ordering an Array of JavaScript Objects in a Custom Sequence (utilizing pre-existing methods)

Imagine we have an array of objects: ["c", "a", "b", "d"] Is there a way in ECMAScript or through a third-party JavaScript library to rearrange the objects in the first array to match the order specified by the second array, all within one line or functi ...

display the $scope as undefined in an angular application

Below is my code snippet: var exchange = angular.module('app', []); exchange.controller('ExchangeController', ExchangeController); function ExchangeController($scope, $http) { $scope.items = []; $http ...

Regular expressions won't produce a match if the string is empty

At present, I am employing the regular expression /^[a-zA-Z.+-. ']+$/ to ascertain the validity of incoming strings. If the incoming string is devoid of content or solely comprises whitespace characters, my objective is for the code to generate an er ...

Strategies for accessing array elements based on category

I am currently working with an array of diverse products var productList = [ { id: '1', category: 'todos', menuName: 'Empanada de Carne, Pollo o Mixta + Café 8oz.', menuPrice: '9.99&a ...

Encountering a hydration issue with an SVG element embedded within a Link component in Next

I'm encountering a hydration error related to an icon within a link, Here is the error message: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <svg ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

The $stateParams are incomplete due to missing parameters

Here, I am attempting to send an object using $state and retrieve it in $stateParams. Despite following the recommended approach from various sources, I am facing difficulty accessing it in the next Controller. Even after researching extensively and readi ...

Ways to add a line break within JavaScript code

I am currently developing a bot for my Discord server and working on logging messages to a text file. All the necessary information about the message is stored in a variable named logger, and I am using Node.js to append my log file. When attempting to ad ...

Encountering a problem with Selenium when dealing with tabular data displayed in a DIV format on a website, where each row is encapsulated within its own DIV element

While creating Selenium automation tests for a website with multiple rows contained within a main DIV element, each row represented by a separate DIV. For example, if there are 5 dynamically generated rows, the HTML code structure would look like this: < ...

Steps for resetting data() on a route without parameters:

Having trouble restarting a route on a new editor I have a specific route /editor as well as /editor?_id=dasd448846acsca The /editor route consists of a simple form with empty inputs, while the /editor?_id=dasd448846acsca route has the same component bu ...

Using Vue.js to Authenticate Users with JWT Tokens Sent in Registration Emails

Hey everyone, I could really use some assistance with JWT tokens. I created a registration form using Vue.js and sent the data to the database using axios. Now, I need help figuring out how to save the token I receive in the confirmation email so that I ca ...

json request not functioning properly in Internet Explorer and experiencing difficulties with caching

Unfortunately, the code snippet provided below is compatible only with Firefox and not Internet Explorer. The JSON file breaks when it encounters the text "Meanscoil na mBraithre Criostaí": "2028425":[19, "Awaiting Correction", "", "Meanscoil na mBra ...

What is the process of converting exactPageList from any to any[] before assigning it to pagefield?

Encountering an issue with paging on my angular 7 app where I am unable to assign exactpagelist of any type to pagefield of type array. The problem seems to be occurring on the last line of the function totalNoOfPages at this point: this.pageField = this ...

Assigning alphanumeric characters to the axis for identification purposes

review the code in index.html <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { stroke: lightgrey; opacity: 0.7; } .grid path { stroke-width: 0; } .ch ...

What is the best method for extracting the innerHTML value of html tags using a css selector or xpath?

I am currently struggling with retrieving the HTML inner text value using CSS selector or XPath. While I can achieve this using document.getElementById, I am unable to do so using selectors. I can only print the tag element but not the text from it. For e ...

What is the process of implementing session storage in an AngularJS directive?

I am trying to save values in Angular session storage within an Angular directive, but I am facing an issue where I only receive NULL. Can anyone provide assistance? app.directive('myDirective', function (httpPostFactory) { return { restrict ...

How do we insert an element into an array with a fixed memory size?

Recently, I reached the Algorithm section of JavaScript and learned that an array cannot grow. However, I am confused about how we can push items into an array. Is the "array" copied and new memory added for additional items? ...

Messages traced by log4javascript are not being displayed

I am currently utilizing log4javascript version 1.4.3. Everything in my application seems to be functioning correctly with all log levels except for trace. To simplify the troubleshooting process and ensure that the issue does not lie within my applicati ...