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

163
Vistas
Me gustaría usar una variable fuera de una función con búsqueda en Javascript

Me gustaría usar una función y luego devolver un valor. Esta función fue escrita en un script en un Javascript externo llamado "tools_4.js".

Aquí está el código de tools_4.js:

 function sendIso3Info(inCurrency) { let iso3Info = { 'text': inCurrency, } einenWert = 'Hallo'; fetch(`/processIso3Info/${JSON.stringify(iso3Info)}`) .then(function(response) { return response.text(); }) .then(function(text) { console.log('GET response text:'); einenWert = text; console.log('This is the value in the fetch') console.log(einenWert); }) .then(function(text) { data_function(einenWert); //calling and passing to another function data_function }) //another functions function data_function(data) { console.log('ich bin in der neuen Funkion!'); alert(data); temp = data; console.log(temp); } console.log('Value outside of the function'); console.log(temp); return temp; }

Estaba usando la función de búsqueda para convertirme en el valor. Pero no puedo usar la variable "temp", porque está escrito "indefinido". Estaba intentando con una variable global, pero no funciona.

aquí está el código de la app.py:

 ######## imports ########## from flask import Flask, jsonify, request, render_template import currencys import json app = Flask(__name__) @app.route('/') def home_page(): example_embed='This string is from python' return render_template('index.html', embed=example_embed) ######## Data fetch ############ @app.route('/processIso3Info/<string:iso3Info>', methods=['GET','POST']) def processIso3(iso3Info): if request.method == 'POST': # POST request print(request.get_text()) # parse as text return 'OK', 200 else: # GET request iso3InfoCurrency = json.loads(iso3Info) out = currencys.return_iso3(iso3InfoCurrency['text']) return out app.run(debug=True)

y el código de la plantilla:

 <head> </head> <body> <h1> Python Fetch Example</h1> <p id='embed'>{{embed}}</p> <p id='mylog'/> <script type="text/javascript" src="{{ url_for('static', filename='tools_4.js') }} </script> <script> iso3Text = sendIso3Info('Euro'); </script> <body>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Obviamente estás confundido por la ejecución de código asíncrono. Aclaremos lo que sucede:

 function sendIso3Info(inCurrency) { let iso3Info = { 'text': inCurrency, } einenWert = 'Hallo'; //1) there, the code will not stop it's execution. //A fetch request takes ages at computer time scale to execute. So the code execution //will not stop there. fetch(`/processIso3Info/${JSON.stringify(iso3Info)}`) .then(function (response) { //3) the promise resolve return response.text(); }).then(function (text) { //4 that other promise resolve console.log('GET response text:'); einenWert = text; console.log('This is the value in the fetch') console.log(einenWert); }).then( //5 Then, this one. function(text){ //you call finaly your function data_function(einenWert); //calling and passing to another function data_function }) //another functions function data_function(data){ //6 even if you assing something to temp, the sendIso3Info already returned //ages ago. console.log('ich bin in der neuen Funkion!'); alert(data); temp = data; console.log(temp); } //2) So, when you get there, temp is still undefined since fetch() can't resolve as fast. Your function will return before the fetch resolves. console.log('Value outside of the function'); console.log(temp); return temp; }

Ahora, ¿cómo resolver tu problema?

Hay algunas formas de hacerlo.

El esaier es usar funciones async :

 async function sendIso3Info(inCurrency) { let iso3Info = { 'text': inCurrency, } //Since we are in an async function, we can explicitly await for other asynchronous call to resolve const response = await fetch(`/processIso3Info/${JSON.stringify(iso3Info)}`); return await response.text(); }

Y para usar su función asíncrona, puede hacer lo siguiente:

 sendIso3Info('Euro').then(res => console.log(res)); //or (async() => { console.log(await sendIso3Info('Euro')); })();
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