Friends, please tell the newcomer how to return the value of out'a? in fact, there are names of twich channels; this function would be desirable if it would return an array of json objects obtained from the given channels names

function getMasApi(mas) { var out = []; mas.forEach(function(el, i) { $.getJSON(api + el, function(json) { //console.log(json); out.push(json); //console.log(out); }); }); console.log(out); return out; }; var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; let api = "https://wind-bow.glitch.me/twitch-api/channels/"; getMasApi(channels); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Reported as a duplicate by members Igor , Air , Bald , ThisMan , Alex on Mar 2 '18 at 13:21 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

     const getChannelsArray = () => { const channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; let channelArray = []; channels.forEach((channel) => { $.getJSON(`https://wind-bow.glitch.me/twitch-api/channels/${channel}`, (data) => { channelArray.push(data); // Для наглядности вызову функцию, которая отобразит результаты (одно свойство объекта в качестве примера) на странице viewResult(data.name); }) }); return channelArray; } const out = getChannelsArray(); //нужный вам массив //Функция отображения данных на странице (для наглядности) function viewResult(data) { $('.text').append(`<li>${data}</li>`); } 
     <ul class="text"></ul> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    • if, before return channelArray, you try to output to the console: console.log (channelArray) it will print '[]'. this is where the question is - the target array is not filled in - Dima
    • @Dima is asynchronous code. While your JSON request is being made, the code goes below. And the line with console.log () is executed faster than the response comes from the server and your array is filled. All your code needs to be executed AFTER you receive a response from the server (data). - Roman Tatarinov
    • Yes, I wanted to get an answer how to make everything consistently implemented, figured out a bit in promises - implemented, I will post soon, I am interested in your opinion by the way - Dima