首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript变量作用域和函数作用域

Javascript变量作用域和函数作用域
EN

Stack Overflow用户
提问于 2022-07-11 20:46:22
回答 1查看 40关注 0票数 -4

下面是代码,我在文件中全局声明了贵重物品,然后将值分配给带有in函数的变量。但是当我试图读取函数之外的变量时,它给出了一个未定义的变量。

代码语言:javascript
复制
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
}

为什么会这样?

EN

回答 1

Stack Overflow用户

发布于 2022-07-11 20:47:31

它不能工作,因为函数是async,而不是await

代码语言:javascript
复制
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)。

代码语言:javascript
复制
let latitude, longitude, IPLocation;
start(path).then(() => {
  console.log(IPLocation) // should work now
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72944480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档