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

166
Views
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 answers
Answer question

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 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!