我想在Javascript中使用fetch函数之外的变量



我想使用一个函数然后返回一个值。这个函数是在一个名为"tools_4.js"的外部Javascript脚本中编写的。

下面列出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;
}

我正在使用fetch函数来成为值。但是我不能使用变量"temp",因为它写的是"undefined"。我正在尝试一个全局变量,但它不起作用?

下面是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)

和模板的代码:

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

您显然对异步代码执行感到困惑。让我们弄清楚发生了什么:


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;
}

现在,如何解决你的问题?

有一些方法可以做到。

使用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();
}

使用async函数,你可以这样做:


sendIso3Info('Euro').then(res => console.log(res));
//or
(async() => {
console.log(await sendIso3Info('Euro'));
})();

相关内容

  • 没有找到相关文章

最新更新