Is it possible to retrieve a variable from outside a `.then` block within a promise?

I'm currently developing a Spotify application. I've successfully implemented the login functionality and obtained my token. However, I have encountered an issue where I am unable to access a specific variable outside of a method, in this case being "getCurrentUser".

Below is the method causing me trouble:


function getUser() {
  if ($localStorage.token == undefined) {
    throw alert("Not logged in");
  } else {
    Spotify.getCurrentUser().then(function(data) {
      var names = JSON.stringify(data.data.display_name);
      console.log(names)
    })
  }
};

Although I am able to log the name variable correctly in the console, when I call the getUser() function, it returns undefined. Even with attempting to return the names variable, I still encounter the same issue.

The solution I am seeking involves utilizing $scope for that variable.

Answer №1

getUser() method is failing to return any value. To fix this, you need to ensure that the promise returned by Spotify.getCurrentUser() is properly handled and the value is returned within the outer function.

function getUser() {

    if ($localStorage.token == undefined) {
        throw alert("Not logged in");
    }
    else {
        return Spotify.getCurrentUser().then(function(data) {
            var names = JSON.stringify(data.data.display_name);
            console.log(names)
            return names;
        })
    }
}

The explanation above addresses the issue of receiving undefined when calling getUser(). However, to utilize the end result effectively, you must adjust how you handle the value from getUser - it returns a promise object, not the final result. Therefore, your code should invoke the promise's then method once the promise is resolved:

getUser()                        // this returns a promise...
   .then(function(names) {       // `names` contains the resolved value from the promise...
      $scope.names = names;      // now you can assign it to your $scope
   });

Answer №2

By following this approach, you can make use of the await function

function fetchUser() {

    if ($localStorage.token == undefined) {
        throw alert("User not logged in");
    }
    else {
        return Spotify.getUserDetails().then(function(response) {
            var userNames = JSON.stringify(response.data.displayName);
            console.log(userNames)
            return userNames;
        });
    }
}

const userNames = await fetchUser();

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

Vuejs dropdown selections are not working as expected due to a bug

My dropdown menu is being populated with options based on an API response that looks like the following: {"value":"1371","label":"apple"},{"value":"1371","label":"banana"},{&qu ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

Adjusting the color of a specific part of a text within a string using

I am trying to update the color of specific keywords within a post. For example: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempor lacinia urna eget gravida. Quisque magna nulla, fermentum fermentum od #keyword1 #keyword2 #keyword3 ...

How to choose the desired day within a specific month when creating a calendar from scratch?

Hi there! I need some assistance. I'm currently working on enhancing a calendar by adding an extra feature. The idea is that when the user selects one or more days, those specific day(s) should be highlighted. However, I'm facing an issue where s ...

Utilizing Q for Node.js promise handling

I am currently working on a Node application where I need to utilize promises for handling asynchronous calls. Although I have a foreach loop inside a .then(function()) of a promise, I am facing an issue where I am unable to return the final result of the ...

Regularly monitoring the existence of a file using AJAX in Django

A new feature has been added to my application built in Django. The feature allows users to input an Elasticsearch query on a form located on the site, which then generates a report for them to download. Everything was running smoothly until we encountered ...

Next.js allows for passing dynamically loaded server-side data to all components for easy access

(I've recently started working with Next.js and inherited a project built using it, so please forgive me if this is something obvious that I'm missing) I have a set of data that needs to be loaded server-side on each request. Initially, I had im ...

Is there a way to implement an event listener for a customized select element within a table on a webpage?

I have a table that contains columns populated from a database. I also have a custom select dropdown in one of the columns, along with an update button. I want to create an event listener for the button that captures the user's selection from the cust ...

The JavaScript feature designed for activating modal popups is only effective for the initial item

I am in the process of developing a clothing shopping website where the main page displays various clothing items. Each garment has an "Add to Cart" button that triggers a popup modal when clicked. However, I am encountering an issue where the modal only ...

Quicker way to apply appendChild

Is there a more efficient method to simplify the process of creating elements from an object fetched via a request? While the current code is functional, it seems overly verbose for what appears to be a straightforward task. async function getJobs() { ...

Ways to Adjust the Earth's Position in WebGL Earth

I have been working with this WebGL Earth component for my project, but I am facing difficulty in adjusting the position of the planet on the canvas. My intention was to place the planet at the bottom of the page, but I haven't been able to achieve th ...

Step-by-step guide on sending JSON data to a server using AJAX and jQuery

Encountering Error While Trying to Send 'Order' JSON Data to JSON File on Node.js Server Everything seems fine with the GET request, but when attempting a POST request, the 'Error' function is triggered instead of the 'success&apo ...

The $location.search parameter does not get updated immediately

The issue I am facing is that my URL does not update every time I set it. Strangely, this seems to be related to the directive, as it works in other cases. Therefore, I am wondering what the $location.search('dd', val) function is dependent on a ...

Implementing Maximum Character Limit on Input Text Fields with AngularJS

Is there a way to use AngularJS to set a maximum value for an amount field? If the user enters a value greater than 10, I want to display an error message next to the textbox. However, because the type is set to "text," this validation is not working as e ...

I designed a dropdown menu with a searchable <mat-select> feature, where selecting an item is automatic when a space bar is pressed in the search box

Description : I have implemented a dropdown list using element that contains a list of items along with a search field. This allows users to easily search for specific items in the list instead of manually scrolling through a long dropdown menu. They can ...

Creating a unique and persistent URL that redirects to a custom array of random user-defined URLs

I've been on the hunt for an online tool that can generate a unique link redirecting to a set of user-defined URLs. Check out to see the concept I'm aiming for. The drawback with that site is its limitation to only inputting 2 links. I'm l ...

How Can You Change the Position of a Threejs Vector3?

I'm attempting to create bones and then manipulate the vertices of each bone, but I am struggling with the correct syntax. Here is an example of what I have tried: var v = new THREE.Vector3(0,0,0); var b = new THREE.Bone(); b.position.x = 5; b.positi ...

"Utilizing Rails 3 to initiate an AJAX submit when radio buttons are changed leads to the generation of

Need help with Rails 3 form partial <%= form_for(answer, :remote => true) do |f| %> <% if answer.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(answer.errors.count, "error") %> prevented this ans ...

Trouble with Angular Material

I have been experimenting with the demo for Angular Material toolbar. The default JavaScript code does not include any dependent modules, as shown below: angular.module('MyApp') .controller('AppCtrl', function($scope) { }); However, ...

Exploring the Power of Streams in JavaScript

I'm looking to create a stream object that can perform the following actions: // a -------1------2----3 // map -----\------\----\ // b --------2------4----6 const a = new Stream(); const b = a.map(value => value * 2); b.subscribe( ...