Promises/Fetch in JavaScript: how to extract text from text file

走远了吗. 提交于 2020-07-18 10:59:05

问题


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

this is
a sample
text file.

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?


回答1:


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:

  • Determine how you want to read the body of the response based on the headers.
  • Stream the response progressively etc.

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);
});



回答2:


Use async/await

async function getSampleText() {
  console.log( (await fetch('sample.txt')).text() );
  console.log( (await fetch('sample2.txt')).text() );
}


来源:https://stackoverflow.com/questions/50401390/promises-fetch-in-javascript-how-to-extract-text-from-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!