JavaScript中的承诺/提取:如何从文本文件中提取文本 [英] Promises/Fetch in JavaScript: how to extract text from text file
问题描述
我正在使用JavaScript编写一个小程序.基本上,我想使用Promise和fetch从两个文本文件中提取文本.但是,我不知道如何从文件中获取实际的文本.这是我当前的代码.
I'm working on a small program in JavaScript. Basically, I want to use Promise and fetch to extract text out of two text files. However, I can't figure out how to get the actual text out of the files. Here's my current code.
sample.txt
sample.txt
this is
a sample
text file.
sample2.txt
sample2.txt
this is
the second
sample file.
index.js
function getSampleText() {
Promise.all([
fetch('sample.txt'),
fetch('sample2.txt')
]).then(allResp => {
let sampleResp = allResp[0];
let sample2Resp = allResp[1];
console.log(sampleResp);
console.log(sample2Resp);
})
}
这是应许...我该如何从中获取文字?
Here are the Promises...how do I get the text out of these?
推荐答案
Fetch不会为响应文本返回承诺-在标头包含后,它会返回对 Response
对象可用的承诺已收到.
Fetch doesn't return a promise for the text of a response - it returns a promise for a Response
object available after headers have been received.
这样您就可以做一些很酷的事情,例如:
This is so you can do cool things like:
- 根据标题确定如何读取响应的正文.
- 逐步发送响应等.
如果您想要响应的文本-您可以 .text()
Response
对象来获得承诺:
If you want the text of the response - you can .text()
the Response
objects to get a promise for that:
Promise.all([
fetch('sample.txt').then(x => x.text()),
fetch('sample2.txt').then(x => x.text())
]).then(([sampleResp, sample2Resp]) => {
console.log(sampleResp);
console.log(sample2Resp);
});
这篇关于JavaScript中的承诺/提取:如何从文本文件中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!