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

children blocking clicks on their parents' divs

I previously asked a question about a parent div not responding to click events because its children were blocking it. Unfortunately, I couldn't recreate the issue without sharing a lot of code, which I didn't want to do. However, since I am stil ...

What is the best way to set a new value in AngularJS?

I attempted to connect the values of msg1 and msg2 like this, and it worked as expected. When I change the input text value of msg1, msg2 also changes to the same value as msg1. Javascript var BindController = function($scope){ $scope.msg1; $scop ...

Verify if the JSON attribute is empty

My input contains the following: { "headers": { ... }, "body": { "RequestInfo": { ... , "Identificator": null } } <filter regex="false" source="boolean($ctx:Identificator)"> - check if it exists (even when it's ...

Preserve JSON information using Ajax

Here is the current code snippet I am working with: Play.save = function() { //Hide the buttons this.printButton.visible = false; this.saveButton.visible = false; this.backButton.visible = false; //Force the game to re-render. th ...

An uncomplicated broadcasting and receiving method utilizing an event emitter

This code is from chapter 3, example 11 of the book Node.JS in Action, found on page 52. var events = require('events'); var net = require('net'); var channel = new events.EventEmitter(); channel.clients = {}; channel.subscriptions = ...

I must break free! Angular's $sce is failing to manage links to audio files (Strict Contextual Escaping)

I have successfully implemented Angular and $sce in my project to handle HTML special characters and link video files in the database to a video player. However, I am facing issues connecting the HTML audio player to audio files stored in the same database ...

AngularJS - Custom directive to add user input to a dynamic list and connect it to a data model

Achieving the goal: In order to associate multiple email addresses with different frequency settings (daily, weekly, monthly) to a notification, I am working on defining a directive. This directive should take the email address from an input element and th ...

What is the best way to divide a string that includes commas into separate parts?

When splitting input strings by commas using .split(','), I encountered an issue with strings that contain commas within a single name. For example: "John, Smith". Typically, my strings appear like this: "Emily, Sasha Flora, Camille-O'neal" ...

The functionality of Javascript Regular Expressions is not performing as expected

I am currently facing an issue with email validation in JavaScript as it doesn't seem to be working properly. PROBLEM: Even when entering a VALID email address, the alert still shows that my address is faulty... What could I possibly be missing he ...

Unable to modify the styles of nested Material UI components

I am currently customizing the styles of the card and cardContent components in material ui. I have implemented them within functional components and am facing an issue with overriding the root style of each component. Specifically, I am struggling to modi ...

Error message: "Attempting to assign a value to the 'size' property of an undefined object, despite the fact that

I recently started delving into NodeJS development and have configured Visual Studio Code for JavaScript development in node applications. During a Pluralsight lecture on Objects, the instructor demonstrated creating two scripts, dice.js and program.js, a ...

Choosing a populated control using JavaScript results in an empty value

Within my ASP.NET applications, I incorporate a server-side HTML select control. <select id="CompanyDropDown" runat="server" style="width:330px"> </select> To populate and pre-select items in this control, I use a JavaScript function triggere ...

What is the best way to completely reset a personalized AJAX object?

I've been passing AJAX parameters through a new object and then using that object with jQuery's $.ajax(). However, I'm struggling to fully reset the object. Despite knowing there must be a simple and elegant solution, I haven't been abl ...

Extracting the value from a Text Editor in React Js: [Code snippet provided]

Currently, I am in the process of developing a basic app that generates a JSON form. So far, I have successfully incorporated sections for basic details and employment information. The basic details section consists of two input fields: First Name and Las ...

Jest does not support util.promisify(setTimeout) functionality

While I understand there may be similar questions on SO, I believe mine is unique and hasn't been addressed in the current answers. I'm currently experimenting with testing a REST API in Express.JS. Below, you'll find a basic working exampl ...

Utilizing Grunt to streamline a personalized project

I have set up Grunt as my "JS Task Runner". Node.js is installed in the directory "C:/Program Files". NPM has been installed in C:/users/Peterson/appdata/roaming/npm. Inside the npm folder, I have Grunt, Bower, and Grunt-cli. I am working on a pro ...

Is there a way to enclose a mention within a unique span tag after highlighting it? Similar to how tags are implemented on platforms such

Currently utilizing an AngularJS plugin called ment.io for incorporating mentions. However, I am having difficulty figuring out how to customize the appearance of the selected mention. For example, in Stackoverflow: https://i.sstatic.net/bZrkh.png Or i ...

What is the best way to have child controllers load sequentially within ng-repeat?

Currently, I have a main controller that retrieves data containing x and y coordinates of a table (rows and columns). Each cell has a child controller responsible for preparing the values it will display based on the x and y values from the parent control ...

Is there a way to retrieve posts by year and month using nextjs and contentful?

Currently, I am in the process of setting up a blog using Next.js and Contentful CMS. The structure of my folders is set as follows: pages/blog/[year]/[month]/[slug].js Each year and month folder contains its own index.js file. Currently, my focus is on ...

Updating multiple collections in MongoDBRestructuring data across multiple

Imagine a scenario where an API call must update two different collections. It's crucial that if one update fails, the first update needs to be reverted. How can I guarantee that both operations either complete successfully or none at all? Let me prov ...