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

86
Views
Obtener respuesta de datos de fetch cuando se crea como módulo javascript en mi código

He estado intentando durante días que una función creada como módulo pueda devolver los datos.

Uso matraz y en una página estoy cargando el módulo en el encabezado.

 <script src="{{url_for('static', filename = 'js/modules.js')}}"></script>

En mi primer intento en el archivo modules.js tengo esta función:

 function send_to_backend_old(data){ let coucou = fetch('/toronto', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(function(response) { response.json().then(function(data_received) { return data_received; }).then((data_received)=>{ return data_received; }) }); return coucou

En la página html dentro de la parte de javascript cuando llamo a la función, estos datos no llegan.

 <button type="button" class="btn btn-primary btn-sm" onclick="pruebas_fetch_to_backend();">fetch módulo</button> function pruebas_fetch_to_backend(){ let datos_json = {}; datos_json.url_api = '/toronto' datos_json.test1 = 'valor1' datos_json.test2 = 'valor2' console.log("---------------------------------------------") riri = send_to_backend(datos_json) console.log("valor de riri: "+JSON.stringify(riri)) console.log("---------------------------------------------") }

la otra prueba es la siguiente:

 async function send_to_backend(data) { let apiResponse = await fetch("/toronto", { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); let response = apiResponse.json(); // Since we waited for our API to respond using await // The response variable will return the response from the API // And not a promise. console.log(response); return Promise.all(response); }

¿Cómo puedo obtener la respuesta cuando llamo a la función desde el código javascript en la página html?

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

0

Funciones como fetch(...) y .json() son funciones asíncronas. Estos devuelven un objeto de tipo Promesa. Esto significa que el resultado de la función no se devuelve inmediatamente.
Con await se puede await el resultado final y luego se puede usar. Las funciones que utilizan la palabra clave await deben definirse como asíncronas.

 async function sendFetchRequest() { const data = await fetchJSONData({ test1: 'value1', test2: 'value2' }); console.log(data); }

Sin embargo, como alternativa a await , también se puede pasar una función de devolución de llamada a una llamada .then(...) . Entonces, una función síncrona también se puede usar para llamar a una función asíncrona.
En este caso, una función síncrona devuelve un objeto Promise resultante de la devolución de llamada de la llamada de recuperación asíncrona. El objeto devuelto luego se espera en la función anterior y se descarga después de obtener el resultado final.

 function fetchJSONData(data) { return fetch('/echo', { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(resp => { return resp.ok && resp.json() }); }

Para detectar un error, existe la opción de usar un bloque try-catch, así como el uso de una devolución de llamada dentro de .catch(...) .

Entonces, un ejemplo simple se vería así.

JS (estático/js/module.js)
 function fetchJSONData(data) { return fetch('/echo', { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(resp => { return resp.ok && resp.json() }); }
HTML (plantillas/index.html)
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Index</title> <script src="{{url_for('static', filename='js/module.js')}}"></script> </head> <body> <button type="button" onclick="sendFetchRequest()">Click me!</button> <script type="text/javascript"> async function sendFetchRequest() { const data = await fetchJSONData({ test1: 'value1', test2: 'value2' }); console.log(data); } </script> </body> </html>
Matraz (app.py)
 from flask import ( Flask, jsonify, render_template, request, ) app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.post('/echo') def echo(): return jsonify(request.json)
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!