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

Is there a way to remove a value from the search bar while updating the table at the same time?

Although I can successfully search the table based on the values in my search bar, I am having trouble with updating the state when deleting a value. To see my code in action, check out my sandbox here. ...

The calculator is experiencing issues with JavaScript functionality

Having some trouble developing a calculator using HTML5, CSS, and JavaScript. After passing my HTML and CSS through validators successfully, I encountered issues when adding JavaScript functions to enable the functionality of the buttons on the calculator. ...

Is the parameter retrieval method correct or erroneous?

I am looking to retrieve data by clicking a link. Here are the links available: <a class="note" id="' . $data["p_id"] . '" value="1" href="javascript:void(0)">+1</a> <a class="note" id="' . $data["p_id"] . '" value="-1" ...

Tips for removing the current item from a list by clicking on a close icon of the same class name

Is there a way to remove a list item after clicking on its close icon? I am using a JavaScript function to add items to the list. Please refer to the image and code below. Thank you! https://i.stack.imgur.com/aeASd.png The code snippet is as follows: f ...

In what way can an array be assigned to a new key within the same key along with additional objects?

My goal is to transform the existing key value into a new format within the same key. It may be difficult for me to explain clearly through words, but the following data will help clarify. The data is currently structured as follows: const sampelData = [{ ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...

Guide on implementing ng-repeat within a nested JSON structure in your Ionic app

Struggling with implementing ng-repeat in a nested json object. { "title": "Important message 01", "img": "any url image here", "authorPhoto": "http://lorempixel.com/40/40/people/4/", "author": "John Doe", "datePos ...

Troubleshooting Angular Reactive Forms: Issue with Binding Dynamic Select Dropdown Value

I currently have two arrays of data: AssociatedPrincipals, which contains previously saved data, and ReferencePrincipals, which consists of static data to populate dropdown controls. I am facing difficulties in displaying/selecting the previous value from ...

Tips for adjusting the horizontal position of a grid item within a map() loop

I am trying to align the text in my Timeline component from Material Ui always towards the center of the timeline. The TimelineContent contains Paper, Typography (for title and description), and an image. Currently, I have multiple TimelineContent element ...

Leverage the retrieved JSON data from the database within an HTML template using the Play

Currently, I am facing a challenge with implementing a login feature in my project. I am struggling to figure out how to showcase the JSON string that is returned on the webpage. Below is a snippet of my code: Security.java: public Person webLogin(Perso ...

Ensure the CSS class stays on Quill clipboard.dangerouslyPasteHTML

One of the challenges I face with using the Quill Text Editor is that when I use the method clipboard.dangerouslyPasteHTML to paste HTML into the editor, it does not maintain custom CSS classes. For example: let content= '<p class="perso-clas ...

Exploring the world of form interactions in Angular: A guide to creating dynamic element communication

I have created a form using Angular, and I want to display a specific value in my input field when an element is selected from the dropdown. Additionally, since the values in the dropdown are fetched from a server, I want to show a corresponding label for ...

Learn the technique of looping through multiple HTML elements and wrapping them in Vue.js easily!

i need to wrap 2 HTML elements together Here is my code snippet using Vue.js <tr> <th v-for="(item9,index) in product_all" :key="item9.id"><center>Qty</center></th> <th v-for="(item99,index) in product_all" :key=" ...

The reason behind the delay in discord.js interactions caused by the "foreach" method

I'm just starting out with JavaScript programming and I have a Discord bot where one of the commands is supposed to silence everyone in a call. However, I noticed that the command first silences five users, creates a pause, and then proceeds to silenc ...

I am having an issue with an input field not reflecting the data from the Redux state in my React app,

I am currently working on a todo list project using the MERN stack with Redux for state management. One issue I am facing is that the checkboxes for completed tasks are not reflecting the correct state from Redux when the page loads. Even though some tasks ...

In MUI v5, the Autocomplete default value is not set

When I try to use the defaultValue prop in the Autocomplete component of MUI v5, the value always ends up being undefined. This is a snippet from my code: const vehicles = [ { name: "Toyota", model: "Camry" }, { name: "Ford&qu ...

Having trouble establishing a default route with React Router v5

I am facing an issue with setting the default route to the home page in react router v5. Despite trying several methods, I cannot get it to work as expected. Index.js import React from "react"; import ReactDOM from "react-dom"; import ...

How to use Javascript to toggle a popup containing an autoplaying Vimeo video

I am looking to create a pop-up window containing a Vimeo video inside. I have a div on my webpage with an id of "showVideo". When this div is clicked, I want to display a pop-up (new div with the id of "opened-video"). The "opened-video" div contains an i ...

Adjust the x-axis on the Vue.js bar chart

I'm currently working on a Vue.js Laravel application where I am trying to incorporate a bar chart using the ApexCharts module. <apexchart ref="apexChart" :options="chartOptions" :series="chartData" type="bar" ...

Fixing Cross-Browser Issues with the OnScroll Function

window.onscroll = function() { if( window.XMLHttpRequest ) { var bodyId=document.getElementById('bodymain'); if (bodyId.scrollTop > 187) { //make some div's position fixed } else { //mak ...