0

I have been using a short function in all my javascript routines to read text files on my local server

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

Works fine, returns the text, but keeps getting pinged as "deprecated" Is there a simple fetch function that could replace this...

I've messed with it and tried various sites for some insight. I get the console.log to registers the file but my 'returns' are always 'undefined' before the console.log fills...

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

Thanks...

  • you aren't returning the result of the fetch ... you are returning `textString` **before** the fetch is made ... that's asynchrony - you need to `return fetch(path).then(response => response.text())` ... now you'll have a Promise that resolves to the text you want – Jaromanda X May 31 '21 at 02:50

1 Answers1

0

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

hopefully this helps

  • Thanks for the help...I can get the response into the console.log (or write it into a div ) but have been unable to get it to 'return'...Perhaps the 'return' happens before 'content' has been created...So still working on it... – Code Clown May 31 '21 at 22:41