为什么我的 fetch 在第一次调用时返回错误,但在后续调用中从未返回错误?
Why does my fetch returned an error the first time it is called but never for subsequent calls?
当我在下面的 运行 时,它第一次运行时出现“未捕获的类型错误:无法读取未定义的 属性 '0'”,但第二次以上运行良好。为什么会这样,我该如何避免。
at HTMLButtonElement.newtexttotype
function newtexttotype () {
fetch('https://developer.nps.gov/api/v1/parks?stateCode=ca&api_key=APIKEYHERE')
.then(response => response.json())
.then(data => {newtexthere = data.data});
console.log(newtexthere[0].description);
}
简单地说,从 URL 中获取数据是一个 异步操作 - 需要一些时间才能完成。
您第一次 运行 代码时,当您执行 console.log 时,数据尚未到达并且您的数组尚未填充。
当您第二次单击 运行 时,请求已完成并且信息已存在。
如何解决?
我不知道您是否知道,但是您的 fetch
调用正在返回一个承诺,这是处理异步操作的一种方式。 promise 公开了一个 .then
方法,您可以在其中放置代码,一旦您的 promise 成功完成其工作,就会 运行。
因此,您应该将 console.log 移到 .then
中,以确保在您登录时,您需要的信息已经存在。
fetch('https://developer.nps.gov/api/v1/parks?stateCode=ca&api_key=APIKEYHERE')
.then(response => response.json())
.then(data => {newtexthere = data.data})
.then(()=> console.log(newtexthere[0].description));
当我在下面的 运行 时,它第一次运行时出现“未捕获的类型错误:无法读取未定义的 属性 '0'”,但第二次以上运行良好。为什么会这样,我该如何避免。
at HTMLButtonElement.newtexttotype
function newtexttotype () {
fetch('https://developer.nps.gov/api/v1/parks?stateCode=ca&api_key=APIKEYHERE')
.then(response => response.json())
.then(data => {newtexthere = data.data});
console.log(newtexthere[0].description);
}
简单地说,从 URL 中获取数据是一个 异步操作 - 需要一些时间才能完成。
您第一次 运行 代码时,当您执行 console.log 时,数据尚未到达并且您的数组尚未填充。 当您第二次单击 运行 时,请求已完成并且信息已存在。
如何解决?
我不知道您是否知道,但是您的 fetch
调用正在返回一个承诺,这是处理异步操作的一种方式。 promise 公开了一个 .then
方法,您可以在其中放置代码,一旦您的 promise 成功完成其工作,就会 运行。
因此,您应该将 console.log 移到 .then
中,以确保在您登录时,您需要的信息已经存在。
fetch('https://developer.nps.gov/api/v1/parks?stateCode=ca&api_key=APIKEYHERE')
.then(response => response.json())
.then(data => {newtexthere = data.data})
.then(()=> console.log(newtexthere[0].description));