Troubleshooting issues with promises not functioning properly in JavaScript

I'm currently developing an application that interacts with Spotify's API. Here is the outline of what I am aiming to achieve:

  1. The user inputs an artist, and I retrieve the corresponding Spotify ID.
  2. Using that ID, I search for related artists.
  3. I save the top tracks of each of those related artists.
  4. Then, I compile a playlist consisting of those songs for a specific user.

This process needs to be executed in a specific sequence (known as synchronously). Recently, I came across Promises, which seem to allow chaining functions together to ensure they run in order. However, I'm still unclear on how to implement them effectively.

Here is my attempt at utilizing Promises:

angular.module('smart-spot', [])
    .controller('MainCtrl', [
        '$scope', '$http',
        function($scope, $http)
        {
            $scope.createPlaylist = function()
            {
                var artist = $scope.artist;
                console.log(artist);
                window.open("/login", "Playlist Creation", 'WIDTH=400, HEIGHT=500');
                var artistId;
                getArtistId(artist)
                    .then(function(response) //this is where the below error is referring to
                    {
                        artistId = response.data;
                        getRelatedArtists(artistId)
                            .then(function(response)
                            {
                                //The chaining seems to be ineffective here.
                            }, function(error)
                            {
                                return $q.reject(error);
                            })
                    }, function(error)
                    {
                        return $q.reject(error);
                    });
            };
            var getArtistId = function(artist)
            {
                $http.get('/search', { params:{ artist:artist } })
                    .then(function(response)
                    {
                        console.log(response);
                        return response;
                    }, function(error)
                    {
                        return $q.reject(error);
                    });
            };

            var getRelatedArtists = function(artist)
            {
                //Retrieve the related artists
            }
        }
    ]);

Upon inspecting the console, I encounter an error stating

TypeError: Cannot read property 'then' of undefined
on the indicated line above. Thus, my attempts to chain these functions together do not yield the desired outcome.

What could I be overlooking?

Answer №1

It seems like your getArtistId function is not returning a promise object because it uses ajax. In order to fix this, you can return the same promise that is returned by the $http.get() call.

$scope.createPlaylist = function() {
  var artist = $scope.artist;
  console.log(artist);
  window.open("/login", "Playlist Creation", 'WIDTH=400, HEIGHT=500');
  var artistId;
  getArtistId(artist)
    .then(function(response) //the error is related to this part
      {
        artistId = response.data;
        //getRelatedArtists also needs to return a promise
        getRelatedArtists(artistId)
          .then(function(response) {
          }, function(error) {
            //you can handle the error here
          })
      },
      function(error) {
        //no need to return anything here; you can display an error message to the user if needed
      });
};
var getArtistId = function(artist) {
  return $http.get('/search', {
    params: {
      artist: artist
    }
  });
};

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

Creating a popup trigger in ReactJS to activate when the browser tab is closed

I am currently working on an enrollment form that requires customer information. If a user fills out half of the form and then attempts to close the tab, I want to trigger a popup giving them the option to save and exit or simply exit. While I have a jQue ...

Connect information to a drop-down menu using AngularJS

For some reason, I am facing an issue when attempting to bind data to a form using AngularJS. I have utilized ajax to retrieve book information and all categories from the database, assigning them to the variable $scope in the controller. While some fields ...

Navbar currently active does not switch when moving to a different page

I'm experiencing some issues with the Navbar on my website. I want the active tab to change as users navigate through the different pages. Since I'm using a base template, I don't want to duplicate the navbar HTML/CSS for each page, so I th ...

Secure AJAX call to PHP service in WordPress, with proper authentication

I have a basic website that utilizes d3.js to generate graphs. The graph data is retrieved via AJAX from a php service using GET requests with specific parameters. The php service then responds with the data in JSON format. Now, I am looking to secure thi ...

Include new options to the select box only if they are not already listed

I'm currently working on a situation where I need to transfer items from one select element to another, but only if they are not already in the second select: $('#srcSelect option:selected').appendTo('#dstSelect') My challenge is ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

How can I filter rows in HTML using Vue.js based on string options?

When selecting different options, I want to dynamically add new rows. For instance, if "kfc" is selected, a specific row should be added. If "cemrt" is chosen, another row needs to be included. <div class="card-content" v-for="(bok, index) in rules" :k ...

Version 2 of the Microsoft Logo Animation

I made some changes to my Microsoft logo animation project. You can view the updated version on CodePen. Overall, I'm pretty happy with how it turned out except for one issue. I'm struggling to determine the right timing to end the animation so ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

Tutorial on moving a bullet towards the cursor in Phaser 3

Currently, I am working on developing a 2D game and facing a challenge in making the bullets move towards the cursor. Here is the code snippet that I have been using: let xDist = this.game.input.mousePointer.x - this.x; let yDist = this.game.input.mousePo ...

Utilizing Bootstrap and JavaScript features to showcase specific tab data

I am currently designing a universal search page. Users input a search query, and all relevant results are displayed. However, I also want to incorporate tabs that users can click on to filter the results further. Currently, the only tab that is functional ...

Angular and RxJS work together to repeat actions even when an HTTP request is only partially successful

I am currently attempting to achieve the following: Initiate a stop request using a stored ID in the URL. Send a request with a new ID in the URL and save this new ID. If the response code is 200, proceed as normal. If it is 204, repeat steps 1 and 2 with ...

How come React-Native isn't displaying successfully retrieved data using Axios?

I recently installed axios using the command below: npm i axios After writing the code below, I encountered an issue where React-Native doesn't display any data or throw any errors: import React, {useState, useEffect} from 'react'; import a ...

Combining the first name, last name, and code in Javascript

I'm attempting to combine the initial letter of both names with the randomly generated code. var firstname = prompt("Please input your first name."); var lastname = prompt ("Please input your last name."); if (amountCorrect >= 4){ ...

Using variables in Javascript to manipulate the Date object

Here is my JavaScript code snippet: var earlierdate = new Date(2012, 09, 22); alert(earlierdate.getDay()); var date2 = new Date('2012, 09, 22'); alert(date2.getDay()); The issue I am facing is that the first alert displays 1 or Monday (incorr ...

Use the .replace() method to eliminate all content on the page except for the table

Extracting a table from a page that has been loaded through .ajax() in queue.htm has proven to be challenging. I am attempting to utilize .replace(regex) in order to isolate the specific table needed, but the process is unfamiliar to me. $j.ajax({ ...

JavaScript problem with incrementing a counter

My React app has a state variable initialized to 0. const [quantity, setQuantity] = useState(0) The goal is to manage product additions and removals in a Redux store. When a user clicks the "+" button, it should check if the quantity is greater ...

Having trouble executing partial views with node.js and AngularJS?

I have been working on my AngularJS application and everything functions correctly when I browse it. However, I've encountered an issue while trying to configure Express. The main page displays fine, but when I click on the hyperlinks to load partial ...

Tips for parsing HTML in React Native

Looking for a way to parse HTML strings into nodes like this? Our society reflects, and is a reflection of, the <del>individual</del><add>person</add> (you and I) , and the <del>individual</del><add>person</add ...