0

I've two files.

FILE 1:

<!DOCTYPE html>
<html>
  <body>
    <button class="add">Click Here!</button>
    <script>
      let a;
      async function test(file) {
        let response = await fetch(file);
        return response.text();
      }
      const bu = document.querySelector(".add");
      bu.addEventListener("click", async () => {
        a = test("./prova.html");
        console.log(a);
      });
    </script>
  </body>
</html>

FILE 2:

<h1>Hello, World!</h1>

When I click the button I want to pass the text body of response from fetch to the var a. But what i get instead is

index.html:16 Promise {<pending>}
dhruw lalan
  • 791
  • 1
  • 11
  • 23
  • `response.text()` always returns a promise, which can either be fulfilled or pending depending on the success of the request ... You need to get the data of the fetch() request, this is not the same as an XHR request in which the responseText is the same regardless, Try using response.data – Cypherjac Jan 31 '21 at 10:19

2 Answers2

1

Async functions return a Promise. A Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. If you want to set the result of it (the actual text after it is retrieved) to variable a you can use the await operator to await the result of test("./prova.html");.

bu.addEventListener("click", async () => {
   a = await test("./prova.html");
   console.log(a);
});
Basa
  • 101
  • 3
  • 9
0

Every fetch request requires a Promise, you should use

  async function test(file) {
    let response = await fetch(file);
    .then(res => ( this.text = res ))
  }

You can find more here : https://medium.com/cleverprogrammer/using-the-javascript-fetch-method-to-get-data-from-an-api-mini-project-10c0d602dae5

Flash
  • 169
  • 1
  • 6
  • When I run your snippet that's the output on console log: Uncaught (in promise) TypeError: Cannot set property 'text' of undefined –  Jan 31 '21 at 10:03
  • What are you trying to achieve? I'm willing to remake ur code to do that. – Flash Jan 31 '21 at 10:08
  • @LorenzoMonaco Replace `this.text` with the reference to the element which of text you want to replace. – Teemu Jan 31 '21 at 10:13
  • @Flash I want to pass the content of file 2 to var a. so var a = '

    Hello, World!

    '
    –  Jan 31 '21 at 10:13
  • @You can't use `a`, everything you do with the response must be done in the function passed to `then`, or you can call another function in that callback, and pass `a`. – Teemu Jan 31 '21 at 10:16
  • something like this maybe? let a; async function test(file) { let response = await fetch("./app.html").then((res) => res.text()); a = response; } console.log(a); –  Jan 31 '21 at 10:18
  • Also, what kind of data is being fetched back, is is text or is it JSON? That could also help in this situation – Cypherjac Jan 31 '21 at 10:22