Waiting for the result of an AngularJS promise

When I click a button in my AngularJS app, the following code is executed:

 if (!$scope.isChecked) {
    $scope.getExistingName($scope.userName).then(function (data) {  
        $scope.userName = data;    
    });
  }

  // Additional processing code followed by another promise  

 myService.save($scope.userName,otherparams).then(function (res) {
       // Redirect to a different page
    }, function (err) {
 });

The problem arises when $scope.isChecked is false, as it enters the promise and before resolving, moves on to the next line of code. This results in $scope.userName not being updated with the new value returned.

I'm seeking suggestions for the best approach to handle this situation. Any advice?

Answer №1

To implement this functionality, utilize the $q service. Begin by injecting $q into your Angular controller.

// Initialize an empty promise
var promise;

if (!$scope.isChecked) {
  promise = $scope.getExistingName($scope.userName).then(function(data) {  
    $scope.userName = data;    
  });
}

// Determine whether to wait for the promise or not, based on its status.
$q.all([promise]).then(function() {

  // Add processing code here and then handle another promise  

  myService.save($scope.userName, otherparams).then(function(res) {
    // Redirect to a specific page
  }, function(err) {
  });
});

Answer №2

If you find that myService.save needs to wait for the $scope.getExistingName promise before completing, simply move that operation inside the "then" statement.

 if (!$scope.isChecked) {
    $scope.getExistingName($scope.userName).then(function (data) {  
         $scope.userName = data;    
         myService.save($scope.userName,otherparams).then(function (res) {
             //route to page
         }, function (err) {
         });
    });
  }

  //some processing code here followed by another promise  

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

Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur: <!DOCTYPE html> <html> <head> <style type="text/css"> .errorcss { background-color: yellow; color:re ...

The differences between using the opacity attribute in HTML and the opacity property

There are two distinct methods for adjusting opacity in HTML: <div opacity="0.5"></div> and <div style="opacity: 0.5;"></div> I am familiar with setting these values in JavaScript as well: div.setAttribute("opacity", 0.5); and ...

JavaScript, Page Method, and GridView are essential components to creating dynamic and interactive

After learning how to use the page method in JavaScript and ASP.Net (VB.Net), I encountered an issue when trying to insert multiple items into a database using a gridview. Despite my efforts, there were no error messages appearing. Here is what I have so f ...

A continuous jQuery method for updating select option values

I'm currently working on a form and using jQuery to make some alterations. The form consists of multiple select elements, and I want to change the value of the first option in each of them. However, as the form allows for dynamic addition of new selec ...

Filtering data from an Ajax request in Angular using a filter function with JSON

Hi everyone, I recently started learning AngularJS and created a basic item list with search functionality and pagination. Everything was working smoothly, so I decided to move my list outside the controller and store it as a JSON file. Here's what ...

Custom Angular-DataTables filter

My goal is to implement a custom filter for angular-DataTables with server-side processing. The sorting and built-in search functionalities of the DataTables are working perfectly for me. I tried following the example on Angular-DataTables to set up serve ...

Finding the Row Number of an HTML Table by Clicking on the Table - Utilizing JQuery

Seeking assistance to tackle this issue. I currently have an HTML table with a clickable event that triggers a dialog box. My goal is to also retrieve the index of the row that was clicked, but the current output is not what I anticipated. //script for the ...

Embedding a table inside a Bootstrap popover

I'm struggling with adding a table inside a Bootstrap popover. When I click on it, the table doesn't show up. This is my first time trying to insert HTML into a popover, so I don't know the correct way to do it. Any help would be appreciated ...

Update a particular package using Node

Is there a way to update Browser-sync without updating all my node packages? I need the version with the Browser-sync GUI, but I don't want to update everything else. ├─┬ <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

What is the reason for Next.js and Gatsby.js necessitating the installation of Node.js, while React.js does not have that requirement?

Have you ever thought about the connection between Next.js and Gatsby.js, both being built on React.js? Could it be that the development environments are Node applications themselves? Or maybe there's something else I'm not seeing? While I have ...

Retrieve the ETag header from a PUT request in AngularJS using $http

Need help getting the ETag header from an AngularJS $http.put request using an S3 MultipartUpload. Struggling to read the value, any assistance is welcome. Thank you! $http({ method: 'PUT', url: url, headers: { 'Content-T ...

Parsing DXF files using only plain JavaScript

Currently, I am immersed in a CNC project and aiming to convert DXF files into objects using JS. Initially, I attempted using SVGs but the results were not as expected - instead of shapes, the drawings exported as lines (e.g., a square appearing as four se ...

What is the method for retrieving the name of a canceled file?

When a user clicks on the "Cancel" button during an upload, I am attempting to retrieve the filename of the file that was canceled. However, it seems like the current method I am using (var image_file_name) is not successfully retrieving the name of the ca ...

The function GetURLParameter(sParam) is displaying %20 as blank space in the webpage

I am facing an issue with a code that pulls URL parameters into the landing page. The problem is that it is including white spaces as %20. For example, if my URL parameter is: example.com/?title=my website, it would display my%20website on the page inste ...

Loading background images in CSS before Nivo slider starts causing a problem

I've been struggling with preloading the background image of my wrapper before the nivo-slider slideshow loads. Despite it being just a fraction of a second delay, my client is quite particular about it -_- After attempting various jQuery and CSS tec ...

Error encountered: Unspecified "from" address in the provided or default options

Seeking guidance on a project related to Ethereum and Solidity, part of Udemy's course titled "Ethereum and Solidity: The Complete Developers Guide." I am currently working on building the front-end for a Kickstarter alternative. I am facing an issue ...

Transform the given text into components applicable to AngularJS

I have a dynamic dashboard with a JSON object that I populate with HTML elements in text format, like this: var items = [ {"id": "panel1", "description": "<div><a ui-sref='page1'>link a</a></div>"}, {"id": "panel2", "de ...

Flot causes the x-axis display to show incorrect time after a certain period of time

Recently, I encountered an issue with jquery flot while working on a real-time chart. Everything seemed to be functioning properly at first, but after some time had passed, I noticed a significant problem. Initially, the chart was updating correctly; howe ...

Converting JSON data types into TypeScript interface data types

Struggling to convert data types to numbers using JSON.parse and the Reviver function. I've experimented with different options and examples, but can't seem to figure out where I'm going wrong. The Typescript interface I'm working with ...

Troubleshooting Tips: Investigating a Service Call in AngularJS 2 using ES6 Syntax

MY DILEMMA: I have recently started learning Angular2 and found myself wanting to debug a service call. The service appears to have been properly called, as evidenced by the view display. However, when trying to log the content of the variable holding t ...