1

I have a function that must validate some artist from Spotify API, but when I run it artists[] remains empty because the function is running asynchronously, 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)
  })
}

function validateArtist(s) {
  let token = localStorage.getItem("Token")
  let url = "https://api.spotify.com/v1/search?type=artist&q=" + s
  console.log(url)
  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 were I call the function, I call it before so it can fill artists

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
    }    
 

What am I missing?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Giackkk
  • 41
  • 6

1 Answers1

2

The async (and await) keywords are tools to manage promises which are, in turn, tools to manage asynchronous code in a standard way.

The use of the async keyword doesn't make a function run asynchronously and not using the keyword doesn't prevent asynchronous code from being so.

fetch runs asynchronously. Your code uses fetch. Therefore your code is asynchronous.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • `async` and `await` are just syntactical sugar of writing promises. – im_tsm Jul 06 '22 at 14:03
  • thanks, how can i make the code wait for the response of setArtist()? – Giackkk Jul 06 '22 at 14:12
  • 1
    @im_tsm — That's a misleading oversimplification. They're used to manage existing promises. They aren't much use for actually writing them, which still needs `new Promise` if you're doing it yourself. – Quentin Jul 06 '22 at 14:23
  • @Giackkk — That's a different question, and one well covered by https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Quentin Jul 06 '22 at 14:23