U
U
Umd232020-11-04 17:02:25
JavaScript
Umd23, 2020-11-04 17:02:25

Why did the global variable array become empty outside of the function?

There is a small node.js script that first gets an id array, then shuffles them, then looks for people's names by id and writes a new array.
But having declared the global variable arrName, it is impossible to display this array in any way, or rather, for some reason it is empty.

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();


Why console.log(arrName);
does it just output an empty array?
Moreover, if I check arrName after the line "arrName.push(array_2);" , then the array is displayed (which is logical 3 times)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AEVZP, 2020-11-04
@Umd23

asynchronous requests.
console.log(arrName) - logged before everything in array_cleaned2 is done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question