1

I am trying to return user from this function which uses another function to open the json file can I return users for the whole function

    function RandomAccount(){
        alert('just confirm');
        readTextFile("./data.json", function(text){
        var data = JSON.parse(text);
        var length = data[0].length;
        // better random
        var i = generateUniqueRandom(length)-1;
        user = data[0][i]['follow_username'];
        return user;
        
    });
   //i want to return user here
    }
  • 2
    You have access to the outer scope. Under your `alert` line you could create a new variable `var myusers = [];` and inside your function you just set `myusers = .....`. The current `return` statement thats in there seems out of place, as this closure is called by the `readTextFile()` function, and i doubt that function desires a "*user*". – Raxi Dec 30 '21 at 22:39
  • 1
    If `readTextFile` is asynchronous, declaring the variable in the outer scope will not work, as the function `RandomAccount` will likely return before the callback function of `readTextFile` is evaluated. In this case, you would need to provide a callback to `RandomAccount` and call that from within `readTextFile`'s callback, or use Promises, for example. – Jacob Mellin Dec 30 '21 at 22:44
  • 2
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – skara9 Dec 30 '21 at 22:52

1 Answers1

1

Declare user before the inline function is called. Example:

function RandomAccount(){
        var user;
        alert('just confirm');
        readTextFile("./data.json", function(text){
        var data = JSON.parse(text);
        var length = data[0].length;
        // better random
        var i = generateUniqueRandom(length)-1;
        user = data[0][i]['follow_username'];
    });
   //i want to return user here
   return user;
    }
  • once I try this it give me an error undefined user .... I want to access one use by doing `let account = randomAccount();` – maxwell kibetz Dec 30 '21 at 22:46
  • 1
    That won't work: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Quentin Dec 30 '21 at 22:55
  • My guess is that `readTextFile` is an anonymous / non-blocking function, in which case `let account = RandomAccount();` will not work, because `RandomAccount` will return before the contents of the callback function `readTextFile` have been executed. You will need to use another callback function, Promises or Async-Await. – Jacob Mellin Dec 30 '21 at 22:55
  • just let me know how I can use this method kindly – maxwell kibetz Dec 31 '21 at 04:41