9阅网

您现在的位置是:首页 > 知识 > 正文

知识

javascript - 对象的类型[重复]

admin2022-11-07知识16
这个问题在这里已经有了答案: 如何从异步调用中返回响应? (39个回答) 为什么我在函数里面修改了我的变量之后,我的变量没有被修改?- 异步代码引用 (6个答案) Chrome 的 JavaScript 控制台在评估数组方面是否偷懒? (7 个回答) 封闭 上月.

我试图从本地txt文件中获取一个文本,并创建一个由该文件中所有单词组成的数组。就像['this', 'is', 'a', 'sample', 'text'...]。问题是,我不能对生成的数组做任何事情。我不能用forEach循环它,甚至不能访问任何项目。我想我应该用某种方式转换数组,但不知道如何转换。这是控制台中数组的截图 可能这个问题很傻,但我对JS很初级。谢谢,我试图从本地的txt文件中获取一个文本,并创建一个由文件中所有单词组成的数组。

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


【回答】:

注意 fetch 是异步的,所以在 then 在您最终的 console.log(arr) 调用。 如果你想对数组中的数据做一些事情,那么应该像这样在Promise链中完成。

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/await 像这样。

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 对象,需要作为异步处理。