Lei*_*ana 4 javascript asynchronous promise fetch-api
我正在使用JavaScript编写一个小程序。基本上,我想使用Promise和fetch从两个文本文件中提取文本。但是,我不知道如何从文件中获取实际的文本。这是我当前的代码。
sample.txt
this is
a sample
text file.
Run Code Online (Sandbox Code Playgroud)
sample2.txt
this is
the second
sample file.
Run Code Online (Sandbox Code Playgroud)
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);
})
}
Run Code Online (Sandbox Code Playgroud)
这是应许...我该如何从中得到建议?
Ben*_*aum 10
Fetch不会为响应文本返回承诺-它Response会在收到标头后为可用对象返回承诺。
这样您就可以做一些很酷的事情,例如:
如果您想要响应的文本,则可以.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);
});
Run Code Online (Sandbox Code Playgroud)