[英]Promises/Fetch in JavaScript: how to extract text from text file
I'm working on a small program in JavaScript.我正在用 JavaScript 开发一个小程序。 Basically, I want to use Promise and fetch to extract text out of two text files.基本上,我想使用 Promise 和 fetch 从两个文本文件中提取文本。 However, I can't figure out how to get the actual text out of the files.但是,我不知道如何从文件中获取实际文本。 Here's my current code.这是我当前的代码。
sample.txt样本.txt
this is
a sample
text file.
sample2.txt样本2.txt
this is
the second
sample file.
index.js索引.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 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. Fetch 不返回响应文本的承诺——它返回一个在收到标头后可用的Response
对象的承诺。
This is so you can do cool things like:这样你就可以做很酷的事情,比如:
If you want the text of the response - you can .text()
the Response
objects to get a promise for that:如果你想要响应的文本 - 你可以.text()
Response
对象来获得一个承诺:
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);
});
Use async/await使用异步/等待
async function getSampleText() {
console.log( (await fetch('sample.txt')).text() );
console.log( (await fetch('sample2.txt')).text() );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.