Nested Promises in Angular's $q Library

I'm facing an issue with a function that should return a list of favorite locations. Here's the code snippet in question:

When I call LocationsFactory.getFavoriteLocations(), it returns a promise like this:

getFavoriteLocations: function() {
                if (favorite_locations.length == 0)
                {
                    var deff = $q.defer();
                    obj.getDeviceId().then(function(device_id) {
                    $http.get('url?token=' + device_id).then(function(response) {
                                 favorite_locations = response.data;
                                 deff.resolve(favorite_locations);
                                 return deff.promise;
                               })
                    })
                } else {
                    return favorite_locations;
                }
            }

The getDeviceId function also uses promises to retrieve a key:

getDeviceId: function() {
  var deff = $q.defer();
  deff.resolve(Keychain.getKey());
  return deff.promise;
}

However, when trying to chain these promises together, I encountered an error saying "TypeError: Cannot read property 'then' of undefined." Can someone provide some guidance on how to resolve this issue?

Answer №1

One great feature is the ability to chain promises together:

        retrieveTopLocations: function () {
            if (top_locations.length === 0) {
                return obj.obtainDeviceId().then(function (device_id) {
                    return $http.get('url?token=' + device_id).then(function (response) {
                         top_locations = response.data;
                         return top_locations;
                    });
                });
            }

            return $q.resolve(top_locations);
        }

You can also enhance this code snippet by:

obtainDeviceId: function() {
    return $q.resolve(Keychain.getKey());
}

Answer №2

$q is not necessary in this case:

if (favorite_locations.length == 0)
{
    return obj.getDeviceId() // a promise must be returned here
        .then(function(device_id) { 
            return $http.get('url?token=' + device_id) // response will be accessed below
        })
        .then(function(response) {
            favorite_locations = response.data;
            return favorite_locations
        });
    })
}

This should resolve the issue.

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

Navigating through a website that loads content dynamically with AJAX can be easily done by

Having an issue with scraping data from a website using jQuery AJAX. There are 300 links to scrape, but the site only shows 50 at a time, requiring scrolling to load more. Can someone assist me with this? var baseURL = "https://hr.myu.umn.edu/psc/hrp ...

Is it more efficient to pass session variables through an ajax function, or should I access them directly within the script?

I am currently working on a page that utilizes an ajax function to retrieve updates from another page. The function requires the user's id, which is obtained from a session variable, to fetch any new updates. These updates are then displayed in a spec ...

Having trouble getting the Babel plugin transform-remove-console to function properly with the Vue CLI 4 and @vue/cli-plugin-babel/preset?

When you create a VueJS project using Vue CLI 4, Babel is configured with a useful preset in babel.config.js: module.exports = { presets: [ '@vue/cli-plugin-babel/preset', ], }; I am attempting to use babel-plugin-transform-remove-conso ...

"Encountering timeout issues with Angular's resource module

I've encountered an issue where a database query called from the backend through the page controller seems to cause an error if it doesn't return immediately. I'm not sure whether the problem lies with Angular or Node.js. Just so you know, ...

Convert the XML response from an API into JSON

Is there a way to convert my XML response into JSON using Angular? This is the response I am working with: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt; &lt;Fer ...

Exploring AngularJS with Jasmine and the Power of $httpBackend

Currently, I am exploring angular and trying to implement automated tests with jasmine. However, I am facing challenges in setting up the test environment. Specifically, my controllers and services are stored in separate files. Here's a breakdown of ...

Jquery animation in Wordpress without any need for scrolling

My Wordpress site features some animations that work flawlessly when the site is scrolled. The code looks like this: jQuery(document).ready(function($){ $(window).scroll( function(){ if(!isMobile) { $('.animate_1').each ...

invoking a function inside a td tag to assign the content

Is there a way to call a function within a <td> element that is part of an ng-repeat in AngularJS? I've tried multiple approaches without success. The problem seems to be with the cartperf.perf_desc binding. <table class="table table-striped ...

What is the best way to extract a specific value from a JSON object?

I'm currently working on building a marketplace using Angular. The main marketplace page is already set up and populated with data from a remote JSON file created with mockapi. However, I've encountered an issue when trying to display a single ra ...

Utilizing material-ui's LocalizationProvider to display times in a different time zone

My application requires material-ui date and time pickers to function based on a remote time zone specified by the server. I want the today circle on the date picker to accurately reflect today in the remote time zone, and I need to convert the datetimes i ...

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

Node.js seems to be having trouble with emitting events and catching them

I'm having trouble troubleshooting my code. // emitter.js var EventEmitter = require('events').EventEmitter; var util = require('util'); function Loadfun(param1, param2, db){ function __error(error, row){ if(error){ ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Attempting to publish and install a unique angular2 component using NPM and Angular-CLI results in successful compilation only on the initial try

I am facing a peculiar and frustrating issue. The problem revolves around an Ng2 component I have developed called via-date-picker. My goal is to publish it on NPM so that it can be easily utilized in other projects. To achieve this, I converted it into a ...

What is preventing comment upvotes from functioning properly? thinkster.io offers tutorials on AngularJS, MEAN stack, and the function incrementUpvote()

Currently, I am working through the Angular JS tutorial provided by thinkster at this link: When attempting to increment the upvote count by clicking on the upvotes icon adjacent to a comment, it fails to execute. Within a ui-router template embedded wit ...

Having trouble with Webpack dynamic import not returning files in ReactJS? Here's how to fix it

Struggling with importing and using images in Reactjs? I've imported all images from a folder but it's not returning an array with links. Take a look. function importAll(r) { return r.keys().map(r); } const images = importAll(requi ...

The controller element in AngularJS becomes undefined when invoked within a directive

Presented below is a snippet of my controller: myApp.controller('WizardController', function ($scope, $http) { $scope.user = { addressline1: null, cobuyer: null, validate: null, cobuyerfirstname: null, cobuyerlastname: null, ...

Experiencing issues utilizing vue.js to retrieve information from a REST API

Using vue.js, I am attempting to fetch data from a rest api but encountering issues. Unfortunately, the response data is not being displayed and no error status is shown either. It's puzzling trying to identify what may have gone wrong. Below is my i ...

The JavaScript object is not being properly posted to the $_POST variable on the PHP page when using vanilla AJAX

Despite my extensive search on the internet and stackoverflow, I have yet to find a solution to my problem. While I understand that JQuery is effective in sending objects, when attempting the same task without the framework, my posts fail to go through to ...

Updating a data with a JavaScript browser script

Recently, I have been attempting to modify the timer in a game using scripts found on various websites. My coding skills are not top-notch, so I am seeking some assistance. I am keeping my fingers crossed that the timer is not server-sided. Upon inspecting ...