Jon Billingsley
Jon Billingsley

Reputation: 1

Javascript - document.write() outside a fetch promise erases what has been written inside it. Why?

There are two blocks of Javascript code. Same fetch, same API. One uses await, the other doesn't. the document.write at the end erases was written in the finally block, but only if I use await, If I don't use await - it adds onto the end.

on the first one the message "promise resolved one way or another" will show up briefly, then after a second, it will be erased and replaced with the next document.write.

Why?

  await fetch("https://catfact.ninja/fact")
     .then(response => response.text())
     .then(result => console.log(result))
     .catch(error => console.log('error', error))
     .finally(document.write("promise resolved one way or another"));

  document.write("<br>code outside the fetch promise"); 

  ```

  ```
   fetch("https://catfact.ninja/fact")
     .then(response => response.text())
     .then(result => console.log(result))
     .catch(error => console.log('error', error))
     .finally(document.write("promise resolved one way or another"));

   document.write("<br>code outside the fetch promise"); 

  ```



Trying to understand why this only happens when I use await. Await pauses the code execution but why does that erase what's been written to the document. 

Upvotes: 0

Views: 54

Answers (1)

M.G.S SUPUNTHAKA
M.G.S SUPUNTHAKA

Reputation: 128

Code block on the finally block will run either there was an exception or even when the fetching done successfully. In the Async - await approach await is not pausing the code execution, It's literally waits till the response comes while not affecting other executions behind the scenes.

I believe the value erases because after finally block it goes to the next line of the code execution and write the next line document.write("<br>code outside the fetch promise");as you have coded in the codeblock.

Upvotes: 0

Related Questions