Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
¿Cómo javascript no devuelve un valor, pero está ahí?

Sospecho que esta pregunta se ha hecho un millón de veces, pero ha sido difícil encontrar la respuesta correcta y no es obvio cómo "obligar" al código a esperar. He visto respuestas que dicen que la sincronización de javascript y la sincronización funcionan como llamar a un amigo para obtener una respuesta, colgar y hacer otra cosa, esperando que el amigo vuelva a llamar. Pero, ¿qué sucede y cómo fuerza al código a esperar esa "devolución de llamada" cuando se ha quedado sin otras tareas pero necesita la respuesta ahora?

Tengo 2 elementos de datos que se devuelven de una llamada de metadatos. Los datos de ambos elementos se muestran en el elemento de metadatos, pero después de la asignación, están en blanco. Pero ambos se muestran cuando se agregan al div.

Aquí está mi código:

 // The fetch call is asynchronous, so define a function that include the await instruction async function fetchJson(API_url) { const response = await fetch(API_url,{ method: "GET", headers: myHeaders }); const json = await response.json(); return json; } // basic metadata for a product const fetchMetadata = (productApiLink) => fetchJson(`${productApiLink}?includeExtendedMetadata=false&includeToc=false`) // create the paragraph elements from metadata let psubtitle = document.createElement('p'); let pdesc = document.createElement('p'); let ptype = document.createElement('p'); // fetch the metadata for the current report fetchMetadata(reports.products[i].apiLink).then(metadata => { psubtitle.textContent = metadata.subtitle; ptype.textContent = metadata.type; console.log(ptype.textContent); // take first 20 words of description, stripping out any html tags pdesc.textContent = metadata.description.replace(/(<([^>]+)>)/gi, "").split(/\s+/).slice(0,20).join(" ") + "..."; console.log(metadata); }) // both elements are blank here console.log(ptype.textContent); console.log(pdesc.textContent); // putting it all together // both show in the div! div.appendChild(ptitle); div.appendChild(psubtitle); div.appendChild(ptype); main.appendChild(div); }

Gracias por ayudarme a entender. Ha sido una lucha leer y probar tantas de estas respuestas que simplemente no funcionan para mí.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!