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

262
Views
variable indefinida que viene en fetch api javascript mientras almacena su valor en una variable
<!DOCTYPE html> <head> <title>home</title> </head> <body> <h1>login here</h1> <form id="createuserform" method="post"> <label>First Name: </label> <input id="fname" type="test"></br> <label>Last Name: </label> <input id="lname" type="text"></br> <label>Location: </label> <input id="location" type="text"></br> <input id="createUser" type="button" value="create user"></br> <input id="setter" type="text" value="val"> </form> <script> function submitValue() { var r; fetch('http://localhost:8080/multimediaApi/api/multimedia/users').then(response => (response.json())).then(data => r = data[0]); document.getElementById("setter").value = r; } </script> <button onclick="submitValue()">Get Data</button> </body> </html>

Quiero obtener los datos de la URL de la API anterior y almacenarlos en la variable r . Entonces, he usado then(data => r= data[0]) para asignar valor a la variable r . y luego mostrarlo en el campo de textfield document.getElementById("setter").value=r . Pero el valor del valor en r viene como undefined .

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

En la ejecución de la función submitValue , el valor de r no estará undefined e iniciará una solicitud AJAX que se completará en algún momento más tarde, y el valor se asigna a

 document.getElementById( "setter" ).value = r;

no estará undefined cuál es el valor actual de r .


Later some time the request is completed

Entonces, el siguiente código se ejecuta

 fetch( 'http://localhost:8080/multimediaApi/api/multimedia/users' ) .then( response => ( response.json() ) ) // now run .then( data => r = data[0] ); // now run

En esto, solo está asignando los data[0] a r . El código de descanso ya se ejecutó antes y no se volverá a ejecutar. Así es como funciona ASYNC JS.

Debería leer Comprender el objeto de promesa de JavaScript

Puede asignar directamente los data[0] al elemento HTML con id setter como:

 function submitValue() { fetch( 'http://localhost:8080/multimediaApi/api/multimedia/users' ) .then( response => ( response.json() ) ) .then(data => { document.getElementById( "setter" ).value = data[0]; }) }
about 4 years ago · Juan Pablo Isaza Report
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!