What could be causing my $q resolution and promise to not function as expected?

I'm constantly facing issues with $q

Here is an instance where the .then is triggered immediately

    function performAction() {
            var deferred = $q.defer();

            var modalInstance = $modal.open({
                template: '<p>this is a modal</p><a ng-click="ok()">ok</a>',
                controller: function ($scope, $modalInstance) {
                    $scope.ok = function () {
                        $modalInstance.close();
                    };
                }
            });

            modalInstance.result.then(function () {
                console.log('ok');
                deferred.resolve();
            }, function () {
                console.log('Modal dismissed');
            });

            return deferred.promise;
        }

In another part of the code:

    $scope.service.performAction().then(
                $scope.variable = 5
            );

http://jsfiddle.net/IngoVals/stqwanhm/

When I tried to replicate a similar scenario in Fiddle, I encountered this issue where .then did not execute. Can anyone explain what might be happening here?

Answer №1

When you update the scope property outside of the then callback, it doesn't fire right away. Take a look at this code snippet:

$scope.service.doit().then(
    $scope.variable = 5
);

This code is incorrect. It should be written like this instead:

$scope.service.doit().then(function() {
    $scope.variable = 5
});

Another issue to watch out for is the so-called deferred anti-pattern. Make sure to avoid creating redundant deferred objects like in the example below:

function doit() {
    return $modal.open({
        template: '<p>this is modal</p><a ng-click="ok()">ok</a>',
        controller: function ($scope, $modalInstance) {
            $scope.ok = function () {
                $modalInstance.close();
            };
        }
    }).result.then(function () {
        console.log('ok');
    }, function () {
        console.log('Modal dismissed');
    });
}

Check out the demo here: http://jsfiddle.net/stqwanhm/2/

Answer №2

The value being passed into then here is 5:

$scope.service.doit().then(
    $scope.variable = 5
);

This code functions as follows:

  1. $scope.variable is set to the value of 5

  2. The result of this assignment (which is 5) is then passed into then

Both of these actions take place immediately when then is called, without waiting for the promise to be resolved.

The intention was to pass a function into then, which would then set the variable:

$scope.service.doit().then(function() {
    $scope.variable = 5
});

By passing in a function, the code within that function will only run when it is called later upon resolution of the promise.

Updated Fiddle Link

In ES6, things become more concise with the introduction of "fat arrow" functions:

$scope.service.doit().then(() => $scope.variable = 5);

This syntax also creates a function and passes it into then (in an ES6-supported environment).

While this conciseness is helpful, it can also be easy to overlook when reading the code. :-)

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

Determining the dimensions of a div once it has completed loading

Is there a way to retrieve the width and height of a div after it has fully loaded, rather than before? I am currently using JavaScript to get the dimensions, but it seems to be returning the values before the image has finished loading. How can I rectify ...

Is utilizing reactivity on static objects practical in Vue 3?

I am currently working with a variable rules that contains an object used for validating a form. After doing some research by reading blogs and watching tutorials, I have come to understand that ref is typically used for primitive values, while reactive is ...

When the jQuery button is clicked, the execute function will run multiple times

I am attempting to create a button using jQuery that calls a JavaScript function, but I am facing an issue : Upon loading the page, the first click on mybutton does not elicit any response The second click results in the function being executed twice On ...

The Bootstrap modal is not properly clearing all attribute properties when it is hidden

Alrighty, so I've got this modal set up: <div id="modal-container" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content center-block" style="displ ...

Leveraging image values for selecting an image from a collection and showcasing it (Javascript)

I have a collection of images that I want to enlarge upon clicking. Here is what I currently have: <div class="gallery"> <div> <img src="content/imggallery/img1.jpg" class="oldimg" value="0"> </div> ...

Adjusting the height of one element based on the height of another element in multiple cases using jQuery

I am currently using jQuery to retrieve the height of one div and apply that value as a CSS property to another. Let's take a look at a sample layout: <div class="row"> <div class="column image"> <img src="image.jpg" /> < ...

Having trouble invoking the .js file with form POST

I've encountered a problem with my code that is technically "working," but it's not functioning as intended. Within the header of my page, I have the following code snippet: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jqu ...

The chosen index in the Material Stepper feature is experiencing a malfunction

I've been busy working on a Mat-Stepper, actually two of them. I have a component that contains two ng-templates set up like this: Question: Why is my selected index not functioning as expected? Am I missing something? I know you can define [selected ...

Adjust the child content within a React component based on the element's width, rather than the overall window size, by implementing dynamic resizing without fixed breakpoints

I am working with a react component that displays a div containing menu items which are aligned horizontally using inline-block. The menu items have text labels "Toy Store", "Configure your Toy", and "About Us". My challenge is to dynamically change the ...

Replace all occurrences of a specific string throughout a extensive document in Node.js

I'm facing a challenge with handling large files in memory. I need to go through each line, replace any double quotes found, and update the file itself. Currently, I am reading the file line by line, storing it in an array, and then overwriting the sa ...

Create a jQuery AJAX call by setting up an HTTP request with specific headers and a request body

Is it possible to create a Jquery request using $.ajax or $.post and include the following information: POST /CreateSpeech HTTP/1.1 Host: tts.eu-west-1.ivonacloud.com Content-type: application/json X-Amz-Date: 20130913T092054Z Authorization: AWS4-HM ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

Ways to transfer data from JavaScript to Wicket framework

My Javascript method executes business logic on the client side and returns a value. I now want to access this value in my Wicket page. What is the most effective approach for achieving this? P.S. I am currently using Wicket 7. ...

Retrieving the object ID of an Open Graph from a page's URL

Is there a way to obtain the Facebook Object ID associated with a page directly from the page itself? For instance, if I requested the Object ID 325186347604922, this is what I received: <pre> { "url": ".../ricetta-bigne_salati.htm", "type": " ...

The ultimate guide to effectively hydrating a React application using code splitting on the client side

Currently, I am in the process of developing a react application and have implemented code splitting on the client side to optimize the bundle. While my application renders correctly on the server side thanks to SSR, I have encountered a warning when utili ...

Steps to retain localStorage data while redirecting to another external webpage

Encountering an issue with saving localStorage data across redirects. See the code snippet below: // Invoke newSitelogin(). Save response(credentials) in localStorage. Redirect to new URL. newSitelogin({ uuid, password }) .then(() => { window.ope ...

When faced with the scenario of having the hashtag in the href attribute and a browser's back button, it

Hello everyone, I've encountered an issue with the "back" action in my browser. When I click on a link, it takes me to a specific page due to a JavaScript function being called. However, when I hit the back button, it simply removes the "#" from the U ...

Is it possible to trim a video using HTML code?

I am trying to find a way to crop a video using HTML 5. <video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video> Currently, the video has a resolution of 640x360. However ...

Creating a function that assigns an anonymous function which in turn returns another anonymous function

Can you explain the difference in JavaScript between these two code snippets? var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { loadData(e.target.result); }; })(file); reader.readAsText(file); a ...

Placing buttons on top of a video within a div container

I am facing a challenge with implementing custom controls on a video embedded in my webpage. I have tried setting a div to absolute position for the buttons, but they are not clickable. Is there a way to achieve this without using jQuery? I need the butto ...