下面是代码,我在文件中全局声明了贵重物品,然后将值分配给带有in函数的变量。但是当我试图读取函数之外的变量时,它给出了一个未定义的变量。
let latitude, longitude, IPLocation;
start(path)
console.log(IPLocation) // not work
async function start(path) {
IPLocation = await getData(path);
latitude = IPLocation.location.lat;
longitude = IPLocation.location.lng;
console.log(IPLocation) // work fine
}
async function getData(path) {
const data = await fetch(path);
const scrampled = await data.json();
parsed = await JSON.parse(JSON.stringify(scrampled));
return parsed
}为什么会这样?
发布于 2022-07-11 20:47:31
它不能工作,因为函数是async,而不是await。
let latitude, longitude, IPLocation;
await start(path)
console.log(IPLocation) // should work now
async function start(path) {
IPLocation = await getData(path);
latitude = IPLocation.location.lat;
longitude = IPLocation.location.lng;
console.log(IPLocation) // work fine
}
async function getData(path) {
const data = await fetch(path);
const scrampled = await data.json();
parsed = await JSON.parse(JSON.stringify(scrampled));
return parsed
}或者,如果您不在模块脚本中(因此您不能拥有顶级await,请使用.then)。
let latitude, longitude, IPLocation;
start(path).then(() => {
console.log(IPLocation) // should work now
})https://stackoverflow.com/questions/72944480
复制相似问题