我正在尝试接收以下代码的输出,其中cc变量会将一个值记录到空的全局国家变量中。然后将其打印到控制台,但是它不起作用。如何将本地变量cc设置为global /为全局变量country赋值?
var country = '';
fetch('https://extreme-ip-lookup.com/json/')
.then( res => res.json())
.then(response => {
var cc = (response.countryCode);
country = cc;
});
console.log(country);
发布于 2020-07-10 21:17:13
你的问题来自于你的fetch是一个异步函数,带有一个promise。
你想做的是(我想)
var country = '';
//then
fetch('https://extreme-ip-lookup.com/json/')
.then( res => res.json())
.then(response => {
var cc = (response.countryCode);
country = cc;
});
//then
console.log(country);但是,由于您使用的是异步函数,因此将执行以下操作:
//first
var country = '';
//second
fetch('https://extreme-ip-lookup.com/json/')
.then( res => res.json())
.then(response => {
//fourth
var cc = (response.countryCode);
country = cc;
});
//third
console.log(country);如何解决这个问题?视情况而定。如果您的console.log是由按钮触发的,请让它等待国家/地区被填写
否则,将您的代码放在最后,或者使用Promise.all() (documentation here)
https://stackoverflow.com/questions/62834790
复制相似问题