【问题标题】:Replacing short XMLHpptRequest with a fetch [duplicate]用 fetch 替换短 XMLHpptRequest [重复]
【发布时间】:2021-05-31 02:46:34
【问题描述】:

我一直在我的所有 javascript 例程中使用一个简短的函数来读取本地服务器上的文本文件

***
function XMLHttp(path) {
    var request = new XMLHttpRequest();
    request.open("GET", path, false);
    request.send(null);
    return request.responseText;
}
***

工作正常,返回文本,但一直被 ping 为“已弃用”是否有一个简单的 fetch 函数可以替代它...

我弄乱了它并尝试了各种网站以获得一些见解。我让 console.log 注册文件,但在 console.log 填充之前我的“返回”总是“未定义”...

***
function fetch1(path) {
  fetch(path)
  .then(response => response.text()) 
  .then(textString => {console.log(textString);
  return textString
  });
}'
***

谢谢...

【问题讨论】:

  • 你没有返回获取的结果......你正在返回textString之前获取......这是异步的 - 你需要@987654324 @ ...现在您将拥有一个可以解析为您想要的文本的 Promise

标签: javascript return fetch text-files


【解决方案1】:

async function fetch1(path) {
  let res = await fetch(path);
  let content = await res.text();
  return content
}

希望这会有所帮助

【讨论】:

  • 感谢您的帮助...我可以将响应写入 console.log (或将其写入 div )但无法将其“返回”...也许是“ return'发生在'content'创建之前......所以仍在努力......
猜你喜欢
  • 2020-05-01
  • 2018-01-31
  • 2016-11-19
  • 2018-10-28
  • 2017-08-19
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
相关资源
最近更新 更多