我正在尝试接收以下代码的输出,其中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:12:16
您的问题似乎与代码的异步性质有关。让我解释一下。
var country = '';
fetch('https://extreme-ip-lookup.com/json/')
.then( res => res.json())
.then(response => {
var cc = (response.countryCode);
country = cc;
});
console.log(country);fetch函数是异步的。这就是您需要.then方法的原因。这意味着当fetch函数运行时,JavaScript不会停止程序的其余部分,而是在fetch()在后台运行时继续运行。因此,当您使用console.log(country)时,它仍然是原始值(空字符串)。
要回答您的问题,可以使用Promises来记录cc的值。
var country = '';
const fetchPromise = fetch('https://extreme-ip-lookup.com/json/')
.then( res => res.json())
.then(response => {
var cc = (response.countryCode);
country = cc;
});
Promise.resolve(fetchPromise) // Waits for fetchPromise to get its value
.then(() => console.log(country))你可以在MDN docs上找到更多关于promises的信息
发布于 2020-07-10 21:20:35
在country设置为response.countryCode之前,当前调用console.log(country)的问题。
您可以通过以下方式将代码放在异步IIFE中来解决此问题:
(async () => {
const response = await fetch('https://extreme-ip-lookup.com/json/');
const ipData = await response.json();
const country = ipData.countryCode;
// place all code that uses `country` in here
console.log(country);
})();
如果您有另一个脚本,其函数定义依赖于county,请确保接受它作为参数,并且不要从全局变量中提取数据。
// helper_functions.js
// Bad
function someFunctionThatUsesCountry() {
console.log(country); // <- don't expect the global to be set
}
// Good
function someFunctionThatUsesCountry(country) {
console.log(country); // pull country ^ from the parameter list
}然后,您可以通过仅传递该值来调用生命周期中的其他脚本。
(async () => {
// ...
someFunctionThatUsesCountry(country);
})();如果因为某些原因非常想要一个全局变量。您应该将promise放在这个变量中,而不是放在值中。有了这个承诺,您可以传递该值,并在该值可用时通知其他脚本。
// script_1.js
window.country = fetch('https://extreme-ip-lookup.com/json/')
.then(response => response.json())
.then(ipData => ipData.countryCode);// script_2.js (must be loaded after script_1.js)
window.country.then(country => { // <- wait until country is available
// do stuff with country
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
复制相似问题