Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
la función asíncrona no espera esperar a buscar

Tengo una función que debe validar algún artista de la API de Spotify, pero cuando la ejecuto, artistas [] permanece vacío porque la función no está esperando la búsqueda, llena la variable usuario sin haber configurado artistas.

 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) } }) }

Aquí es donde llamo a la función, la llamo antes para que pueda llenar la variable de artistas.

 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 }

¿Cómo puedo arreglarlo?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Puedes usar Promise.all() como:

 const artists = ['first', 'second']; const promises = artists.map(artist => fetch(url+artist)); Promise.all(promises) .then(response => { // handle response }) .catch(err);

o

 const returnedData = await Promise.all(promises).catch(err);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Mirando las piezas una a la vez, setArtists debe ser asíncrono y probablemente debería ejecutar la validación actualmente (ya que las validaciones no son interdependientes).

No hay necesidad de que los artists sean globales en el ámbito contenedor. De hecho, tenerlo fomentará los errores.

 // clarifying... input is a comma-delimited string describing artists // validate each one with spotify, and return an array of the valid artists async function setArtists(input) { let parsedInput = input.value.split(",") let promises = parsedInput.map(validateArtist); let results = await Promise.all(promises); // validate all of them at once // return just the valid inputs, not the nulls return results.filter(r => r); }

El método validateArtist mezcla estilos asíncronos. Aquí está con estilo uniforme y con un objetivo más claro: simplemente validar y devolver a un artista...

 // given the params of an artist, lookup on spotify and return a // a promise that resolves to the input artist if valid, null otherwise async function validateArtist(s) { const token = localStorage.getItem("Token") const url = "https://api.spotify.com/v1/search?type=artist&q=" + s console.log(url) const response = await fetch(url, { "method": "GET", "headers": { 'Accept': 'application/json', 'Content-Type': 'application/json', "Authorization": "Bearer " + token, } }); if (response.status === 401) { refreshToken(s) } const searchedResults = await response.json(); const isArtist = searchedResults.artists.items.length != 0; // notice, no side-effects here, resolve to the input artist or null return isArtist ? s : null; }

Por último, la persona que llama también debe ser asíncrona y esperar el resultado de setArtists ...

 async function theCaller() { // notice - no need for a global. now it's a local here... let artists = await 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 } // ...

Como nota al margen, puede haber cosas valiosas en la matriz de artistas que spotify devoluciones, algún superconjunto de los datos con los que consultaste. Si prefiere mantener los resultados, puede crear una política para elegir el primer artista coincidente devuelto en la matriz de coincidencias de Spotify...

 // updating the functional comment: // given the params of an artist, lookup on spotify and return a // a promise that resolves to the first found artist or null if no matches are found .then(searchedResults => { let items = searchedResults.artists.items; return items.length ? items[0] : null; });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda