Search code examples
javascriptarraysasync-awaites6-promisefetch-api

Why non async function is running asynchronously?


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?


Solution

  • 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.