I'm trying to make the users variable that contains an array of usernames usable from outside the fetch. when I do console log inside the fetch I have no problem, the variable appears with its names in array type, the problem is when I try to show the data of the users variable outside the fetch it appears empty. Is there any way to be able to use it to then go through that variable outside of the fetch?
let sliders = document.getElementsByClassName('sliders');
let contentDots = document.querySelector('.content-dots');
let name = document.getElementsByClassName('.name');
let sliderArray = [];
let users = []; // esta variable no puede ser mostrada fuera del fetch
fetch('https://jsonplaceholder.typicode.com/users')
.then(resp => {
console.log(resp.status);
return resp.json();
})
.then(data => {
data.map((persona) => {
let nombres = persona.name;
users.push(nombres);
})
})
for(i = 0; i < sliders.length; i ++) {
sliderArray.push(sliders[i]);
}
for(i = 0; i < sliderArray.length; i++) {
let dots = document.createElement('div');
dots.className += 'dots';
contentDots.append(dots);
console.log(dots);
}
First change the syntax of your fetch and assign it to a variable that I do have access to in the rest of the scope . I don't know the rest of your script structure; that is most likely messing with your variable.
It's for your last then. It's because of the map you're applying. Remember that map does loop but returns an array of what you request; in that loop only what's on your list has scope. Therefore, it is not necessary to push inside.
When we have a fetch request, this is a background call, better known as ajax, what happens in javascript is that the return callback is only captured in the then, which is known as a promise, this is part of your code:
What happens is that the code must be encapsulated with a promise to have those values available and it seems to me that I have a vision of when the request is completed, so I will do the other loops, with usersResolved information that will contain the names.
For the syntax to be as you want, the only way is for everything to be executed inside a function
async
, every time we use theawait
the execution is waiting:if not, you have to use the
then()
, as other users suggested, another option is to cast a function in the callback: