Why does the variable's value reset to empty when leaving the function?

I encountered an issue with my api request that is included in a function within my Service script. Despite defining the variable "curruser" outside of the function to retain its value, I noticed that it becomes empty after exiting the script.

services.js

function fbUserInfo() {
  ngFB.api({
    path: '/me',
    params: {
      fields: '/*params*/'
    }
  }).then(
    function(user) {
      curruser = user;

      $http.get(/*send GET request to my server*/).success(function(response) {
        if (response.length < 20) {
          curruser.firsttime = true;
        } else {
          curruser.firsttime = false;
        }
        console.log(curruser);
        console.log("1");
      });
    },

    function(error) {
      alert('Facebook error: ' + error.error_description);
    });
}

Although the console.log displays the correct JSON object retrieved from Facebook, when I attempt to return it in the statement:

return {
  userInfo: function() {
    fbUserInfo();
    console.log(curruser);
    return curruser;
  }

it shows that curruser is an empty object. I made sure to include

var curruser;

at the beginning of the ".factory" as well.

Answer №1

Ensure to utilize the then() method as fbUserInfo() is an asynchronous function.

return {
  userInfo: function() {
    $.when(fbUserInfo()).then(
function(user) {
  curruser = user;

  $http.get(/*send GET request to my server*/).success(function(response) {
    if (response.length < 20) {
      curruser.firsttime = true;
    } else {
      curruser.firsttime = false;
    }
    console.log(curruser);
    console.log("1");
  });
},

function(error) {
  alert('Facebook error: ' + error.error_description);
}).then(function(){
 console.log(curruser);
    return curruser;
})

  }

Answer №2

Not yet tested, but it has the potential to work.

    var currentUser;
    function getFacebookUserInfo( callback ) {
      ngFB.api({
        path: '/me',
        params: {
          fields: '/*params*/'
        }
      }).then(
        function(user) {
          currentUser = user;

          $http.get(/*send GET request to my server*/).success(function(response) {
            if (response.length < 20) {
              currentUser.firstTimeUser = true;
            } else {
              currentUser.firstTimeUser = false;
            }
            console.log(currentUser);
            console.log("1");
            callback(currentUser);
          });
        },

        function(error) {
          alert('Facebook error: ' + error.error_description);
        });
    }


return {
  userInfo: function( callback ) {
    getFacebookUserInfo( function(data){
       console.log(data);
       callback(data);
    });
  }

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

Restricting the length of dynamic dropdowns in a React application

Click here to view the code on CodeSandbox My dropdown menu options are dynamically generated and filtered based on custom data. const dropdownData = [ { code: "others", name: "Others", amenity: [] }, { code: "bed", name: "Bed", ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

Displaying multiple categories of articles on a single page with Node.js

Seeking a solution to limit the number of posts displayed for each category using a .limit() function, but uncertain on how to proceed. Currently utilizing Mongoose and Express in my code setup. The existing code snippet is outlined below: router.get(&a ...

Ways to ensure the first div always expands when sorting in AngularJS

In my AngularJS application, I have a set of div elements generated using ng-repeat. The first div is always expanded by default upon loading the page. Now, when I click a button to sort the divs based on their ID in the JSON data, I want the top div to ...

Combining various JSON objects by nesting them together

I'm in the process of creating an endpoint where I need to combine data from four different tables into one nested object. Each table record is retrieved in JSON format using sequelize - they include information on location, service, staff, and tenant ...

I encountered an issue while attempting to fetch table data, receiving the following error message: "Uncaught TypeError: result.rows.product is not a function at products.html:134."

https://i.sstatic.net/WZ5CC.pngHere is the HTML I have written <form> <br/> <label for="products1">Product Name:</label> <input type="text" name="pdt" id="pr ...

Can the execute_script function in Python Selenium wait for JavaScript content to fully load before proceeding?

I am currently working on automating a task using Python and Selenium for the Safari browser. The task involves navigating a webpage where clicking on letters from A to Z activates a Javascript function on the page, reloading a table below with stocks that ...

Utilizing Objects as Properties in Phaser.Scene in Phaser 3

I've just started working with Phaser using TypeScript and I'm facing an issue. I attempted to move my main objects out of the create and preload methods by loading them as Phaser.Scene class properties. However, after making this change, my game ...

Full replacement of a cell within an HTML table

I have a scenario like the following: <table id="myTable"> <tr> <td class="1">cell 1</td> <td class="2">cell 2</td> </tr> <tr> <td class="3">cell 3</td> &l ...

Transferring object information to Backand using Ionic 2

I have developed a signup page using Ionic 2. In this signup page, I have included a dropdown menu for users to select their blood type. However, I am facing an issue where the selected blood type is not being sent to the Backand database as expected. I&ap ...

Switching videos upon clicking buttons

Hey there! I've got an interesting challenge for you. I have four mp4 videos featuring a cartoon character performing various emotes. My goal is to create a toggle switch that, when activated, will display the first video (intro) along with three butt ...

Issue with Webpack in vue.js project when incorporating sasssass causing errors

I am new to Vue.js and webpack, and I'm not sure if the issue lies with the packages or my own mistake. Steps to replicate the problem: Create a new Vue project using the webpack template ~ vue init webpack sass-test ? Project name sass-test ? Proj ...

Difficulty arises when trying to extract specific information from an ajax response using the jQuery.filter

The code snippet below seems to be causing some trouble. It's supposed to filter HTML content that includes a div with the class "filtered_entries_box", but it's not working as expected. $.ajax({ "url" : "start.php", "type" : "POST", ...

Repetitive process in JavaScript

I am struggling to write certain attributes to HTML using a recursive loop and I can't seem to get the code to work properly. The JSON data consists of an array of hashes with the following attributes: serno (serial number), parent_serno (serial numb ...

Redux's 'connect' function fails to recognize changes in the state array

I've recently implemented redux with a reducer that handles an array of time slots for a specific date. Whenever the date is changed, the reducer successfully updates the state (confirmed through console logs in my mapStateToProps function). However, ...

What is the best way to utilize the useSWR hook when there are necessary logical operations to be performed on the response before proceeding with the next API call

I am currently utilizing the swr library in a Create React App and require the usage of the useSWR hook for data fetching that is both contingent and conditional. The specific task at hand involves: Making an API call to retrieve an id which will be used ...

Ways to make a $resource in Angular return example data?

Let's imagine I have an angular service with the following resource: var res = $resource('/myurl/:index', {index: '@index'}) Is there a way for me to customize paths so that when I use: $res.query() I receive a predefined outpu ...

Can you please tell me the name of the ??= operator in Typescript?

The Lit Element repository contains a function called range that utilizes the ??= operator. This operator resembles the nullish coalescing operator but with an equal sign. Do you know what this specific operator is called? Below is the complete code snipp ...

What are the reasons behind loading failures and the subsequent failure to resolve promises?

Here is a snippet of code that is part of a larger directive: var imageArray = []; for (var i = 0; i < $scope.abbreviations.length; i++) { imageArray[i] = new Image(); imageArray[i].src = $scope.abbreviations[i].img ...

Looped jQuery setTimeout not functioning correctly

I am facing an issue with processing a JSON file that contains a list of serialized objects. My goal is to walk through this JSON and display the messages from it one at a time, with a delay of 2 seconds between each message before ultimately stopping. I a ...