Utilizing a callback function to update the value of a variable that is declared outside of the getJSON function

I'm currently facing an issue with this function I have.

function customCheck(username){
    var result = "normal";  
    $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){
      if(data.stream == null)
        result = 'offline';
      else 
        result = 'online';

    }).fail(function(){
        result = 'notfound';
       });

   return result;
}

console.log(customCheck('streamer123'));

The problem lies in the fact that when I check the console log, it always displays "default" instead of "offline", "online", or "notfound" as expected.

I've attempted to rearrange the code by moving the console.log() line before the customCheck() function, but unfortunately, it didn't solve the issue. Also, trying to define the variable result globally did not resolve the problem either.

If anyone has any suggestions or solutions, please feel free to share them!

Answer №1

Here is an example of how your code should be structured:

function verifyUser(username, callback){
    var result = "default";  
    $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){
      if(data.stream == null) {
        result = 'offline';
      } else {
        result = 'online';
      }

      callback(result);
    }).fail(function(){
        result = 'notfound';
        callback(result);
    });
}

verifyUser('freecodecamp', function (result) {
    console.log(result);
});

The reason for this structure is that $.getJSON operates asynchronously, meaning it returns immediately and provides its output value through a callback function.

In order to access the final result, you will need to utilize a similar approach by implementing a callback within your own function that executes when the $.getJSON function invokes its internal callback.

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

Generate HTML elements within an AngularJS directive and establish a click event

Can you show me how to create some DOM elements and add a click event to them using an AngularJS directive? My current approach is as follows: var list = document.createElement("div"); list.classList.add('myList'); for(var i = 0; i < n; i++) ...

What impact does adding 'ng' in unit tests have on how promises are handled?

Here is an example of a service that utilizes $q.when to wrap a promise from a third-party library: // myService.js angular.module('myApp', []) .service('myService', function($q, $window) { var api = new $window.MyAPI(); this ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Having difficulty accessing a public array item within chained AXIO transactions in VUE

I am currently facing an issue with a chained AXIOS call that is triggered from an array. The challenge I am encountering is ensuring that the second call completes before the first one initiates another API request, which seems to be working fine so far. ...

The attempt to add a note with a POST request to the /api/notes/addnote endpoint resulted in a

I'm facing an issue while trying to send a POST request to the /api/notes/addnote endpoint. The server is returning a 404 Not Found error. I have checked the backend code and made sure that the endpoint is correctly defined. Here are the specifics of ...

"Is there a way to extract a value from a JSON object using

I have an object with the following key-value pairs: { 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812', 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1&a ...

Input information into a JSON container

I've been struggling to find a solution for this issue. Here's the JSON variable I'm working with, which includes the names "rocky" and "jhon": var names = [ "rocky", "jhon" ]; Now, I need to add a new val ...

The conversion of Draft-js JSON to EditorState is not functioning correctly

Recently, I utilized Draft-js to generate blog posts. When a user creates a post, the data is transformed into a string and dispatched to the server for storage. The conversion of draft-js EditorState looked like this: JSON.stringify(convertToRaw(editorSta ...

Using AngularJS Typeahead with restrictions on $http requests

I have been attempting to restrict the number of results displayed by Angular Bootstrap Typeahead during Async calls, but unfortunately, it does not seem to be functioning as expected. <input type="text" ng-model="asyncSelected" placeholder="Locations ...

Customize the behavior of jQuery cycle with an <a> tag

Can the jQuery cycle be accessed through a link in order to override the i variable? I've come across examples that can achieve this, but not in a scenario like this where the cycle() function is located within a variable: $(document).ready(function ...

Integrating objects into the <select> element through the combination of C#, JavaScript, and HTML connected to a SQL

Can someone assist me in resolving this issue? I am trying to populate an HTML element with database fields using C# and JavaScript, but so far my code is not producing any output. I have also attempted to include a button that calls the "loadGrp" function ...

Responsive menu is failing to respond to the click event

I'm facing an issue with my responsive menu on mobile phones. It should display two buttons - one for the navigation bar and the other to toggle the side bar by removing the classes hidden-xs and hidden-sm. However, I am having trouble getting the btn ...

What is causing the issue with Vue.js :class not functioning properly when it relies on a property of a list

Here is a snippet of my HTML code: <tr v-for="product in products" :class="{'bg-red': product.toWrite }" :key="product.name"> <td @click="setObjectToWrite(product.name)" class="show-hover&qu ...

The URL is being modified, yet the page remains static in the React application

I've been working on setting up a router with react-router-dom, but I'm facing an issue where my URL gets updated without the page routing to the specified component. Here's a snippet from my App.js: import "./App.css"; import { Br ...

Using Object Value as Variable instead of String in JavaScript/React

When working with React & JavaScript, I am storing an input name as a string in an object: window.ObjectOne = { ObjectOneKey: "MyInputName", } The input name can be an object path like "Object.FirstName" or a variable name "MyVariableName" What I am at ...

How can Angular incorporate JSON array values into the current scope?

I am currently working on pushing JSON data into the scope to add to a list without reloading the page. I am using the Ionic framework and infinite scroll feature. Can someone please point out what I am doing wrong and help me figure out how to append new ...

The contrastText property of the MUI React Theme palette is not functioning properly

I am working with MUI React to design a menu and I have utilized the AppBar component. I would like to customize it in the following way: brown.myBrown = '#544846'; const brownTheme = createTheme({ palette: { primary: { ma ...

Interactive search functionality using jQuery

In the panel I have, I would like to include a search input field that allows users to type in a word. As soon as a match is found, that specific word will be highlighted within the panel while the other information disappears. ...

When pressing the next or previous button on the slider, an error message pops up saying "$curr[action] is not a

I found this interesting Js fiddle that I am currently following: http://jsfiddle.net/ryt3nu1v/10/ This is my current result: My project involves creating a slider to display different ages from an array, such as 15, 25, 35, 45, 55. The goal is to show ...

React-Native introduces a new container powered by VirtualizedList

Upon updating to react-native 0.61, a plethora of warnings have started appearing: There are VirtualizedLists nested inside plain ScrollViews with the same orientation - it's recommended to avoid this and use another VirtualizedList-backed container ...