What might be the reason my $q.defer().resolve is not functioning properly?

I have noticed an interesting behavior in my code. When I define a promise in the service and return it back (promise1 in this case), it does not resolve at all.

However, when I define the promise in the controller (promise2), it works perfectly fine. Why is that?

Here is my demo on CodePen

serv.getDefer = function() {
    var defer = $q.defer();
    return {
      defer: defer,
      promise: defer.promise
    }
}

var defer1 = serv.getDefer().defer;
var promise1 = serv.getDefer().promise;
promise1.then(function() {
    alert('promise1 should work, but doesn't')
})
defer1.resolve();

var defer2 = serv.getDefer().defer;
var promise2 = defer2.promise;
promise2.then(function() {
    alert('promise2 works properly')
})
defer2.resolve();

Answer №1

Exploring closures is key here. Each time the function getDefer() is called, it creates a new variable and then returns it.

While untested, this code snippet below might provide a solution:

var def = service.getDefer();
def.promise.then(function() {
    alert('promise1 may work but hasn't been confirmed yet')
});
def.defer.resolve();

Answer №2

Every time you utilize the function serv.getDefer(), it generates a new deferred object. In your first promise, you call serv.getDefer() twice to create both defer1 and promise1. Since these are separate variables, resolving defer1 does not resolve the promise of promise1.

In the second example, promise2 corresponds to the promise of defer2, so resolving defer2 will also resolve the promise.

To correct this issue, you need to follow these steps:

var deferred = serv.getDefer(),
    defer1 = deferred.defer,
    promise1 = deferred.promise;

promise1.then(function() {
  alert('promise1 should work, but it doesn't');
});

defer1.resolve();

Answer №3

defer1 does not create promise1. Instead, a new deferred object is being created by calling getDefer() once again.

promise2 functions correctly as it is generated by defer2.promise()

In my opinion, the correct line should be:

var promise1 = defer1.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

How to use AngularJS ng-options to retrieve the chosen option from an array that corresponds to another variable in the scope

Does anyone know how to create a dropdown select in AngularJS with default selection based on a dynamic value? $scope.fcFeedTypes = [{"name":"Plain Text","value":"Plain Text"},{"name":"MQ Message","value":"MQ Message"}]; } $scope.feedEditor.ft = "MQ Messa ...

Utilize JavaScript to Forward Subdomain to Main Domain

Utilizing Apache envvars, I have created the MYDOMAIN and MYSUBDOMAIN variables to define 'mydomain.com' and 'sub.mydomain.com'. These variables are then used in the Apache sites-available conf files for website deployment. The 'su ...

Instructions for showing a timer on a webpage from a managed bean by utilizing JavaScript

I'm currently tackling the challenge of passing a Date from a managed bean to JavaScript and then displaying it as a timer in the format "hh:mm:ss aa". I've attempted it but so far, no luck. Code: DateTimeManagmentMB.java (Managed Bean) import ...

Trigger a function when the browser automatically populates an input field

I am attempting to trigger a function that can detect if the browser has autofilled a field and then add a specific class to it. After finding a thread with a solution that mostly works, mentioned here: Here is how I implemented it: $.fn.allchange = fun ...

Instructions on converting a SQL expression to Sequelize

Could someone assist with converting this to sequelize? CREATE TABLE "fundraiserUpdates" ( "updateId" SERIAL, "updateFundraiserId" INTEGER NOT NULL, "updateTitle" TEXT NOT NULL, "updateDescription" TEXT NOT NULL, CONSTRAINT "pk_fundraiser ...

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 ...

Verifying the format of an object received from an HTTP service using a TypeScript interface

Ensuring that the structure of the http JSON response aligns with a typescript interface/type is crucial for our javascript integration tests against the backend. Take, for example, our CurrentUser interface: export interface CurrentUser { id: number; ...

Exploring Material UI: Understanding the contrast in functionalities between incorporating the Icon component and the Material Icons node

I am looking to incorporate Material Icons into my application. I have come across two methods provided by Material UI for adding the same icon to my site: Using the <Icon /> component, which is part of the @material-ui/core package: <!-- Add t ...

Storing a collection of items in an array using jQuery

Looking to organize list items from multiple lists of the same class into an array. For example: <ul class="myList"> <li>item 1</li> <li>item 2</li> </ul> <ul class="myList"> <li>i ...

Storing customer information securely on the server with the help of Node.js

After spending some time experimenting with Node.js on my local machine, I've realized that my understanding of HTTP requests and XHR objects is quite limited. One particular challenge I've encountered while using Node is figuring out how to effe ...

What is the most effective way to manage and respond to multiple events while also organizing the overall structure of

I am currently in the process of planning a complex web application using WebGL and Three.js. As I experiment with different tests, I have encountered a problem that is raising many questions for me. I am unsure of the correct approach to take and would gr ...

Prevent users from inserting images from their desktop into the HTML by disabling

While working on a HTML5 drag and drop image uploading feature, everything was going smoothly. I had a small div in the HTML with a JavaScript event handler set up like this: $('#uploader').on('dragover', function(e){ ... }).on(&apos ...

To dynamically switch the login button to a logout state based on certain conditions

Here is the snippet of my login form in the header HTML: <ul class="nav navbar-nav navbar-right" ng-controller="loginController"> <li class="dropdown"> <a href="" class="dropdown-toggle" data-toggle="dropdown" ng-show="$scope.lo ...

Error message: "AngularJS encountered a $injector:modulerr error in Internet Explorer 11."

I've successfully created an AngularJS App that functions properly on most browsers like Firefox, Opera, Safari, Edge, and Chrome. However, there seems to be a compatibility issue with IE 11. When attempting to open the app in IE 11, the following er ...

I was caught off guard by the unusual way an event was used when I passed another parameter alongside it

One interesting thing I have is an event onClick that is defined in one place: <Button onClick={onClickAddTopics(e,dataid)} variant="fab" mini color="primary" aria-label="Add" className={classes.button}> <AddIcon /> & ...

Issues regarding innerHTML

I have a collapsed table with a link that collapses its content. My goal is to change the link (such as from "+" to "-" and vice versa) using JavaScript. I was able to achieve this, but now my table no longer collapses. Here is the code snippet: <div c ...

How to insert a new document into a MongoDB collection with Mongoose

Consider a scenario where my existing collection called fruits is structured as follows: {"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7} {"_id" : ObjectId("abc...."), " ...

When <li> elements are rendered via ajax, it is not possible to attach JavaScript Events to them

Hey there, I've got a drop down menu that's being shown using UL and LI tags. This is generated by a PHP script that echos out: '<li id='. $value .'>'.$value.'</li>' The JQuery function below works perf ...

The Three.js camera imported from Collada is unable to properly focus on an object within the scene

Having some trouble grasping the concept of Collada Animation in Three.js! I have an animation with a moving camera in 3Dsmax, and exported the scene into Collada. loader.load( ColladaName, function ( collada ) { model = collada.scene; model.upda ...

The div structure generated through JavaScript appears distinct from its representation in the live DOM

Currently, I am facing a challenge with creating a complex nested Div structure within a JavaScript loop that iterates over JSON response objects from the Instagram API. The main goal is to set the URL for each image within a specific Bootstrap div layout. ...