Wait for loop to finish $.getJSON for each array item before outputting data
<p>I've got an array of names which I need to retrieve data from, and I'm currently doing this with $.getJSON inside a loop. It works and I can retrieve the data, but to output the correct value I need to use setTimeout or similar. I'm wondering if there's a more refined way of doing what I'm looking to achieve.</p>

<p>Here's what I've got.</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var names = ["riotgames", "example"];
var online = [];

for (var i = 0; i &lt; names.length; i++) {
  $.getJSON('https://api.twitch.tv/kraken/streams/' + names[i], function(data) {
    if (data.stream != null) {
      online.push(data.stream.channel.display_name);
    };
  });
}

console.log(online) // outputs []

setTimeout(function() {
  console.log(online) // outputs correctly
}, 1000);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre>
</div>
</div>
</p>