Is the variable not being initialized outside of the function?

I'm really struggling with this async issue. I can't seem to get it to work because the summonerData array is not being set. I have a feeling it has something to do with async, but I'm not sure how to troubleshoot it.

var summonerName = req.params.playerName;
var summonerData = [];
var summonerIds = [];
var summonerGames = [];
redis.exists(summonerName, function(err, reply) {
    if (reply === 1) {
      console.log('Data Found for Summoner in Redis!: ' + summonerName);
      redis.hgetall(summonerName, function(err, object) {
        summonerData.push(object);
      });
    } else {
      console.log('Data not Found for Summoner: ' + summonerName);
      lolapi.Summoner.getByName(summonerName, function(error, summoner) {
        if (summoner) {
          console.log('Summoner was retrieved by API! and Saved to Redis!');
          redis.hmset(summonerName, summoner[summonerName]);
          summonerData.push(summoner[summonerName]);
        }
      });
    }
});
console.log(summonerData);

Answer №1

Implementing asynchronous functionality involves triggering a function to execute at a later time. By utilizing redis.exists, you are setting up the function to be called in the future, while the subsequent line, console.log(summonerData), executes before the callback is triggered.

To ensure the desired outcome, it is essential to place console.log(summonerData) inside the function itself.

Answer №2

For optimal performance, it is recommended to utilize promises

var fetchSummonerInfo = function (summonerName) {
    return new Promise(function (resolve, reject) {
        var summonerData = [];
        var summonerIds = [];
        var summonerGames = [];
        redis.exists(summonerName, function (err, reply) {

            if (err) {
                return reject(err);
            }

            if (reply === 1) {
                console.log('Data Found for Summoner in Redis!: ' + summonerName);
                redis.hgetall(summonerName, function (err, object) {
                    if (err) {
                        return reject(err);
                    }
                    summonerData.push(object);
                    resolve(summonerData);
                });
            } else {
                console.log('Data not Found for Summoner: ' + summonerName);
                lolapi.Summoner.getByName(summonerName, function (error, summoner) {
                    if (error) {
                        return reject(error);
                    }
                    if (summoner) {
                        console.log('Summoner was retrieved by API! and Saved to Redis!');
                        redis.hmset(summonerName, summoner[summonerName]);
                        summonerData.push(summoner[summonerName]);
                    }
                    resolve(summonerData);
                });
            }
        });
    });
};


fetchSummonerInfo(req.params.playerName)
        .then(function (summonerData) {
                res.render(..., summonerData);
        });

Explore more about promises here:

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

The list of lists is giving an error: "Cannot read property 'name' of undefined."

What am I doing wrong here? let items = [{ name: 'client1' }, { name: 'client2' }, { name: "client3"}]; for (let i = 0; i < items.length; i++) { if (items[i]['name'].includes(self.autocomplete)) { self.box += '<l ...

Identify the index of a list item using a custom list created from buttons

When dealing with a dynamically built list like this: <ul id="shortcuts"> <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li> <li><input type="checkbox" value ...

AngularJS faces issue with view not reflecting changes made to model

A web-based game I am developing lets players bid on cards and trade them with one another. The technology stack for this application includes Node, Express, MongoDB, and Angular. The player avatars and names, along with their connection status, are displ ...

What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below: GetCurrentUserInfo.java package servlet; import java.io.IOException; import java.io.ObjectOutputStream; import java ...

I'm having trouble setting up Stripe Elements in PHP. It seems like there's a communication issue between my PHP code and my JS

New to setting up Stripe Elements, I've followed the documentation closely. Installed the necessary JS modules, included the Stripe API, and connected it to the Stripe JS. In my index.php file, PHP script is at the top with HTML and JavaScript below i ...

The 'click' event is not triggering after adding elements to the DOM using AJAX

$(".btn-close").on('click', function () { alert('click'); var win = $(this).closest("div.window"); var winID = win.attr("id"); $(win).find("*").each(function () { var timerid = $(this).attr("data-timer-id"); ...

Having trouble retrieving JSON data from an external URL in AngularJS when making a $http.get call and using the success method?

Code in the Controller.js file: let myApp=angular.module('myApp',[]); myApp.controller('myController', function($scope,$http){ $http.get('data.json').success(function(data){ $scope.art=data; }); }); ...

Provide Arguments to a Function in Express JS

How's everything going? I'm curious to find out the best way, and if it's possible to send a specific parameter to an express function in NodeJS. I want to pass the string ('admin') or any other string that I choose to the 'R ...

What is the method for displaying data on a browser instead of downloading it when creating a link?

Clicking on this link will trigger the download of the f.txt file. Rather than downloading it, I would like the data to be displayed directly in the browser. For example, when you click this link, the data is shown directly in the browser. While I have ...

Vue.Js for a Single Page Application utilizing Two Data Sources

Currently, I am working on developing a Single Page Application using vue.js. My project consists of 2 bundles of pages stored in separate S3 buckets - one public and one private. The public bundle is meant to be accessible to all users, while the private ...

Two values are returned from the Node.js Mongoose Exports function

Currently, I am encountering an issue with my project where a service I developed is up and running. However, it is not providing the desired value as a response. Specifically, the goal is to generate coffee items linked to specific companies. Whenever new ...

Converting bullet point list to checkboxes once requirements have been satisfied

I am working on developing a password validator with specific regex conditions in Material UI that transitions from bullet points to checkboxes when the criteria are satisfied. Initially, I attempted to use the npm library NiceInputPassword, but it did no ...

Error when sending Angular 4 GET request with multiple Headers results in a 400 bad request code

I've been attempting to perform a POST request with headers in order to receive a response. The Angular code snippet I'm currently using for this request is shown below: const headers = new HttpHeaders({ 'Content-Type': 't ...

Troubles with Promise.all and json() in JavaScript causing errors being logged as "invalid function"

I'm experiencing some difficulties with the "Promise.all" method. Essentially, I have an array of URLs (here is a simple one if you want to test it: const urlArray = [ "https://coverartarchive.org/release/985adeec-a1fd-4e79-899d-10c54b6af299&qu ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

The code generated by Asto SSR may not be compatible with older iOS versions, causing it to fail to run

I have been running my astro SSR site on Netlify with great success. However, I recently encountered an issue when testing it on older iPhone models like the iPhone 6 and earlier. It seems that all script executions halt, rendering the site non-interactive ...

How can I remove markers from google maps?

I have been working on a program that dynamically loads JSON data onto a map as markers when the user pans and zooms. However, I am facing an issue where I need to clear the existing markers each time the user interacts with the map in order to load new on ...

Identifying a shift in data model within a component

It seems like there's a piece I might be overlooking, but here's my current situation - I have data that is being linked to the ngModel input of a component, like so: Typescript: SomeData = { SomeValue: 'bar' } Snippet from the vie ...

How can I reposition an image diagonally to a specific location using JavaScript in p5.js? Is there a method to display an image and then conceal it at a chosen location in p5.js?

Is there a way to move the third image diagonally until it intersects with the two images? var pic1; var pic2; var pic3; let posX=0 let posY=0 const rightwall=350; function preload(){ pic1=loadImage("5.png") pic2=loadImage("iron.jpg&qu ...

Determine if the user has clicked on the Save or Cancel button within the print dialog box

Hello everyone, Can anyone help me figure out how to determine which button was selected by the user in a print dialog box? Thank you! ...