Javascript 对象的类型

Javascript 对象的类型,javascript,arrays,asynchronous,Javascript,Arrays,Asynchronous,我尝试从本地txt文件中获取文本,并创建一个由该文件中的所有单词组成的数组。就像['this','is','a','sample','text'…]。问题是我无法对结果数组执行任何操作。我无法将其与forEach循环,甚至无法访问任何项目。我想我应该以某种方式变换数组,但不知道如何变换。 也许这个问题很傻,但我对JS非常熟悉。谢谢 const arr = [] fetch('sample.txt') .then(response => response.text()) .t

我尝试从本地txt文件中获取文本,并创建一个由该文件中的所有单词组成的数组。就像['this','is','a','sample','text'…]。问题是我无法对结果数组执行任何操作。我无法将其与forEach循环,甚至无法访问任何项目。我想我应该以某种方式变换数组,但不知道如何变换。 也许这个问题很傻,但我对JS非常熟悉。谢谢

const arr = []
fetch('sample.txt')
    .then(response => response.text())
    .then(data => data.split(' '))
    .then(result => arr.push(...result))
console.log(arr)

请注意,
fetch
是异步的,因此在最后的
console.log(arr)
调用之前,
then
函数中的所有操作都不会完成。如果要对数组中的数据执行某些操作,则应在承诺链中执行,如下所示:

const arr = []
fetch('sample.txt')
    .then(response => response.text())
    .then(data => data.split(' '))
    .then(result => arr.push(...result))
    .then(() => {
        console.log(arr)
        arr.forEach(word => console.log(word))
    })
// outside here the array is still empty
async function myFunction {
const arr = []
await fetch('sample.txt')
    .then(response => response.text())
    .then(data => data.split(' '))
    .then(result => arr.push(...result))
arr.forEach(word => console.log(word))
}
如果您想在外部使用它,则可以像这样使用
async/await

const arr = []
fetch('sample.txt')
    .then(response => response.text())
    .then(data => data.split(' '))
    .then(result => arr.push(...result))
    .then(() => {
        console.log(arr)
        arr.forEach(word => console.log(word))
    })
// outside here the array is still empty
async function myFunction {
const arr = []
await fetch('sample.txt')
    .then(response => response.text())
    .then(data => data.split(' '))
    .then(result => arr.push(...result))
arr.forEach(word => console.log(word))
}

这会导致函数的处理等待
fetch
调用(以及所有后续
then
语句)完成后再继续。这样做可以保证
arr
已填充。但是请注意,您必须将函数声明为
async
,这意味着它现在返回一个
Promise
对象,需要将其视为异步对象。

response.text
response.json
此处
。然后(response=>response.text())
?您是如何尝试使用阵列的?您遇到了什么故障?谢谢。但其想法是保存结果数组并在外部使用。我从昨天开始就在搜索解决方案,但仍然没有找到任何结果。要在
获取
之外使用,您可以使用我在下面的回答中描述的aysnc/WAIT,但它会产生连锁反应,您正在使用它的函数现在将返回一个承诺谢谢!我又花了几个小时阅读/观看教程,但现在我明白了它的工作原理。