【问题标题】:Problem when converting the output of Fetch to string (Javascript) [duplicate]将 Fetch 的输出转换为字符串(Javascript)时出现问题 [重复]
【发布时间】:2021-08-04 16:58:19
【问题描述】:

我有一个 txt 文件,其中包含我想要阅读的所有意大利语单词 (link) 的列表,然后将其转换为单词数组,但我有点卡在阅读部分。该文件最初是从网上下载的,因此它可能有也可能没有一些编码问题。

要读取文件,我使用的是 Fetch,与this post 的最佳答案中建议的代码相同。阅读后,如果我使用alert(storedText),则文本正确显示;但是,如果我尝试 var s = storedText.toString() 然后 alert(s) 我在警报框中得到“未定义”。

我猜在读取文件时有一些问题,但我对 JavaScript 比较陌生,我无法弄清楚究竟是什么问题。你们有什么想法吗?

编辑:这是我的完整代码

var storedText;

fetch('http://doodlemarty.unaux.com/wp-content/uploads/2021/08/parole.txt')
  .then(function(response) {
response.setContentType("text/html;charset=UTF-8");
    response.text().then(function(text) {
      storedText = text;
      done();
    });
  });

var s = storedText.toString();
var fullList = storedText.split('\n');

function test () {
//first try:
alert(storedText);
//second try:
alert(s);
//trying split:
alert(fullList[2]);
  };

单击按钮时,我会执行测试功能。

【问题讨论】:

  • 请出示您的代码
  • 为什么需要toString就可以了?它已经是一个字符串。做一个 storedText.split(/\s+/) 得到的话。确保它是 UTF8 并且运行它的页面也有 UTF8 的元标记
  • 我的感觉是你的第一个 alert 在 promise 的 then 处理程序中,但第二个在外面,运行得太早,在这种情况下,这将是 this good old question 的副本,但是我们不看代码就无法判断。
  • @mplungjan 我尝试使用 toString 因为我遇到了拆分方法的问题(我得到了一个“未定义”)
  • @Martina 也很高兴看到这一点

标签: javascript fetch-api


【解决方案1】:

这似乎是一个带有承诺的async 问题。您正在尝试在 fetch 操作中更新其值之前访问 storedText

试试这个:

var storedText;
var s;
var fullList;

async function callFetch() {
    let response = await fetch('http://doodlemarty.unaux.com/wp-content/uploads/2021/08/parole.txt')
    response.setContentType("text/html;charset=UTF-8");
    let text = await response.text();
    storedText = text;
}

function setVariables() {
    s = storedText.toString();
    fullList = storedText.split('\n');
}

async function test() {
    await callFetch();
    setVariables();
    //first try:
    alert(storedText);
    //second try:
    alert(s);
    //trying split:
    alert(fullList[2]);
};

【讨论】:

  • 不需要所有的异步,只需将处理移到数据到达的地方
  • 是的@mplungjan,就是这个想法。用最简单的话来说,就是从 API 获取数据后处理数据。我只是认为异步看起来更具可读性。
  • 非常感谢,成功了!无论如何,为了使其工作,我必须删除调用 response.setContentType 的行...知道为什么吗? (我已经注意到 callFetch 第一行中缺少的分号并修复了它)
  • setContentType 根据规范不支持:developer.mozilla.org/en-US/docs/Web/API/Response fetch.spec.whatwg.org/#response-class 这是服务器端操作(如果您在后端使用节点,请参阅:stackoverflow.com/questions/52812561/…
  • @stWrong 好的,谢谢!
猜你喜欢
  • 2021-12-05
  • 2020-03-17
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多