Is it possible to access variables within functions from outside of them?

async function checkPlayersOnline() {
    const response = await fetch("http://ip:port/dynamic.json");
    const playersData = await response.json();
    console.log(playersData.clients);

    }

Is it possible to access the playersData inside another function? Example:

async function displayPlayers() {
console.log(playersData.clients);
}

When I attempt this, I get undefined as a result.

Answer №1

"Indeed", it is possible:

let data 

async function check_players_online() {
    const response = await fetch("http://ip:port/dynamic.json");
    data = await response.json();
}

async function display_players() {
    // There is no guarantee that data has been set!!!
    console.log(data.clients);
}

But there's no guarantee that the data is already defined at that moment. You need to ensure that check_players_online is called and awaited before you invoke display_players.

You can achieve this by structuring your calls in this order:

async function check_players_online() {
    const response = await fetch("http://ip:port/dynamic.json");
    const data = await response.json();
    await display_players(data)
}

async function display_players(data) {
    console.log(data.clients);
}

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

Events in Backbone View are failing to trigger

Currently, I am incorporating Backbone into a project and facing an issue with getting the events functionality of Backbone Views to function properly. Below is a snippet extracted from my current application: Base File: window.App = Models: {} Vie ...

Mapping out your data effectively requires following the correct steps to ensure accuracy and clarity

My goal is to display a map using Mapbox only once the data is ready. The Vuex store code I am working with is as follows: /store/index.js import Vue from "vue"; import Vuex from "vuex"; import _ from "lodash"; import { bac ...

Phone Validation for Contact Form 7

Recently, I was tasked with creating a landing page for a job interview. The challenge was to include validation on the phone number field so that it has to be between 9 and 10 numbers in length, along with another validation requiring the phone number t ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

Looping through dates in a POST request using JavaScript/GAS - What's the best approach?

My task involves posting timesheet entries for the upcoming month into a system using an API. In order to do this, I require the following: User ID Assignable ID Dates (in the format YYYY-MMM-DD) Hours Initially, I obtained the user_id and assignable_id ...

Is there a way to create an interpolated string using a negative lookahead condition?

When analyzing my code for imports, I will specifically be searching for imports that do not end with -v3. Here are some examples: @ui/components <- this will match @ui/components/forms/field <- this will match @ui/components-v3 ...

Whenever I use Vue JS, I notice that it displays [Object object] on console.log and returns Undefined when

Currently, I'm developing Vue.JS code to showcase data fetched by PHP from a server. The PHP sends a JSON object to the Vue for display. Below is my existing code snippet: axiosPost(); } function axiosPost() { axios.post( './Conver ...

Updating views with AJAX after database updates without the use of jQuery via PHP

Learning MVC and Ajax has been quite an adventure for me. I decided to build a site using PHP and MySQL, where I successfully implemented a new controller method to handle ajax requests. With the help of Ajax HTTPRequest, I am now able to update my databas ...

a new approach for creating a conditional function in pointfree fashion

Can someone help me convert this code into a pointfree style? To provide context: The function receives an Array of Either types and returns a Task type. If any of the Either types have the left set, the Task type is rejected with that value. If none of t ...

There was an error in the syntax: a semicolon is missing before the statement

During an ajax request, I encountered this error and upon reviewing it thoroughly, I am unable to pinpoint the cause. The following code snippet is where the issue seems to lie: $('#post_submit').click(function() { var poster_id = <?php echo ...

Manipulate the text within a swf file using jQuery

Looking for a solution to target links inside a SWF file connected to XML without access to the .fla or .swf files. Is there a way to achieve this using jQuery or Javascript? Any help is appreciated. ...

Adding a checkbox to menu items in a ReactJS application can be accomplished by utilizing specific components

I have successfully created dynamic menus using a recursive function, and they are displaying in the correct order without any issues. Requirement: My current goal is to identify the last level of menus and assign a checkbox with the value corresponding ...

Incorporate href along with ng-click for improved functionality

I need a link that will call a $scope-function when clicked, which will then display another view. I also want the user to be able to right-click on the link and open it in a new window or bookmark it. Unfortunately, the current html code is not worki ...

Transfer the data from one object to another while disregarding any additional properties

I am dealing with 2 objects: person{ name : string gender : string } woman{ name : string } The challenge I face is that I have an object "person" filled with values, and I need to copy those values into a new object "woman" without including the "ge ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

Invoke the click handlers consecutively following the initial click handler using ajax requests

I have a button on my webpage that triggers multiple click events. The button code looks like this: <input type="button" id="myButton"/> There are several functions bound to the button's click event using jQuery: $("#mybutton").on("click", f ...

Can a data filter be customized to fit a specific grid layout, ensuring that all images are displayed in a full column or at a designated size?

Check out this awesome box grid https://i.sstatic.net/qbmQz.jpg But here's the issue: when I add a data filter and switch between filters, the images always appear in the same location and size as the original grid. Is there any way to make the filte ...

Using AJAX to save data while dealing with duplicated forms

Project Details: In the midst of developing an asp.NET web application, I am faced with a challenge. The user interface (UI) I have created allows users to generate multiple instances of an object by inputting data into forms. Consequently, numerous ident ...

dynamic jquery checkbox limit

I am working with the following HTML code: <input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1 <input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2 &l ...

Add a class if the particular class is missing from the webpage

Seeking a solution in JS, I am facing a challenge in creating a series of elements with active states, each opening a caption below when clicked. Utilizing .addClass, .removeClass, and .toggleClass in combination, only one element can be active at a time. ...