I have a function that must validate some artist from Spotify API but, when I run it, artists[] remains empty because the function is not waiting on the fetch: it fills the variable user without having set artists.
let artists = []
function setArtists(input) {
artists.length = 0
let parsedInput = input.value.split(",")
parsedInput.forEach(artist => {
validateArtist(artist)
})
}
async function validateArtist(s) {
let token = localStorage.getItem("Token")
let url = "https://api.spotify.com/v1/search?type=artist&q=" + s
console.log(url)
await fetch(url, {
"method": "GET",
"headers": {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Authorization": "Bearer " + token,
}
})
.then(response => {
if (response.status === 401) {
refreshToken(s)
}
return response.json()
})
.then(searchedResults => searchedResults.artists.items.length != 0)
.then(isArtist => {
if (isArtist) {
artists.push(s)
}
})
}
Here is where I call the function; I call it before so it can fill the artists variable:
setArtists(document.getElementById("artistiPreferiti"))
var user = {
username: document.getElementById("username").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value,
gustiMusicali: document.getElementById("gustiMusicali").value,
artistiPreferiti: artists
}
How can I fix it?
setArtist()function will need to beasyncalso, and it will need toawaitthe validation function call. Something else will have toawaitthe call tosetArtist(), because only after the promise is satisfied will the array be updated as you expect.