【发布时间】:2018-10-28 01:52:00
【问题描述】:
我正在使用 Fetch API 开发一个项目。我想使用 fetch 从文本文件中获取一些数据并将它们放入数组中,以便我可以使用它们。我不确定使用什么代码来使变量成为全局变量。我认为通过在 fetch 语句之外初始化变量,我可能能够以这种方式使用它。到目前为止,这是我所拥有的:
动物.txt
cat
dog
rabbit
index.js
const animalArray;
fetch('animals.txt')
.then((res) => res.text())
.then(data => {
animalArray = data.split(/\r?\n/) //how can I access this outside of the fetch statement?
}
})
【问题讨论】:
-
简而言之,你不能。由于 fetch 是异步的,任何在
.then之外访问animalArray的代码都可能会在 fetch 完成之前运行。任何依赖于获取结果的东西都必须直接或间接地放在.then中。 -
只需将与它们一起使用的代码放在
then回调中即可。
标签: javascript arrays variables global fetch-api