Why did the global variable array become empty outside the function?
-
There is a small script on node.js that first receives an array of id, then mixes them up, then searches for people's names by id and writes a new array.
But by declaring the global variable arrName, it is impossible to display this array, or rather it is empty for some reason.
function shuffle(array) { array.sort(() => Math.random() - 0.5); } const arrName = []; const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; const x = new XMLHttpRequest(); x.open('GET', 'https://slack.com/api/conversations.members?token=xxx&channel=xxx'); x.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); x.onload = function() { let array_1 = JSON.parse(this.responseText).members; shuffle(array_1); var array_cleaned = array_1.filter(function(element) { return element.length <= 9; }); var array_cleaned2 = array_cleaned.filter(function(element2) { const y = new XMLHttpRequest(); y.open('GET', 'https://slack.com/api/users.profile.get?token=xxx&user=' + element2); y.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); y.onload = function() { let array_2 = JSON.parse(this.responseText).profile.display_name; console.log('В группе состоит ' + array_2); arrName.push(array_2); } y.send(); }); console.log(array_cleaned); console.log(arrName); } x.send();
Whyconsole.log (arrName);
outputs just an empty array?
Moreover, if I check arrName after the line "arrName.push (array_2);" , then the array is output (which is logical 3 times)JavaScript Paige Bullock, Dec 18, 2019 -
Asynchronous requests.
console.log (arrName) - displayed before everything in array_cleaned2 is executedAnonymous -
Because you fill it inside the callback, which at the time of the output
console.log (arrName)
has not been called yet.
Put the output after the line
arrName.push (array_2);
to make sure that an empty array is displayed first, and then it starts fillingPaige Calderon
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!