0

I'm spinning my wheels over here. How do I return the new value of onlinearray?

I want it so when I call the functions like so...

online()

I get the result onlinearray handed back to me.

  function online(){
    var offlinearray = [];
    var onlinearray  = [];
    console.log('called online');

    //foreach item in channels
    codeLib.channels().forEach(function(item){
      console.log(item);
      // run gotJSON
      codeLib.gotjson(item).done(function(result){
        if (result.stream == null) {
          // push into offline array
          offlinearray.push(item);
          console.log('OFFLINE array: '+ offlinearray );
        }else{
          // push into online array
          onlinearray.push(item);
          console.log('ONLINE array: ' + onlinearray); <--I can see values in console.log here
        }
      });

    });
    //console.log('inside: '+onlinearray);
    return onlinearray; <---doing something wrong here.
  }

gotjson is as follows...

  Codelib.prototype.gotjson = function(channel) {
     return $.getJSON("https://api.twitch.tv/kraken/streams/"+channel)
  };
Jessi
  • 791
  • 1
  • 12
  • 24
  • I don't see any _closure_ here, it's normal function – Tushar Oct 09 '15 at 21:31
  • Why do you assume the problem is at that line? – Karoly Horvath Oct 09 '15 at 21:31
  • 2
    You can't do that with asynchronous calls. – crush Oct 09 '15 at 21:31
  • `return onlinearray;` will return the array. when you call the function, you need to assign the return value, like so: `var result = online();` – devlin carnate Oct 09 '15 at 21:32
  • could you clarify what does codeLib.channels() do? is it an async call? and gotjson? – rvalerio Oct 09 '15 at 21:33
  • I am guessing, like @crush and @rvalerio that the problem is an async call. `.gotjson` looks like a promise-returning function, My advice would be refactor using promises. – barry-johnson Oct 09 '15 at 21:39
  • BTW - if the collective assumption that these are async functions, the only way you will be able to have something close to your preferred calling syntax (i.e. `var result = online();` would be if you convert the online function to a generator using ES6 (or a ES6 to ES5 transpiler like Babel). – barry-johnson Oct 09 '15 at 21:42
  • I have read the above link...Why is my variable unaltered after I modify it inside of a function? - Asynchronous code ....and I am still no closer to an answer. :( – Jessi Oct 10 '15 at 02:31

0 Answers0