Home > front end >  Javascript Fetch Function returns [object Promise]
Javascript Fetch Function returns [object Promise]

Time:11-12

I'm currently working on a project, which includes a website, built and run by Django. On this website, I'm trying to load data through fast API and try to load this data through JavaScript and the Fetch API. But I always get instead of the Data provided through the API, an [object Promise]. I've tried many different methods but none seem to work.

I've tried for example:

document.getElementById("1.1").innerHTML = fetch('the URL')
 .then(response => response.text())

or

document.getElementById("1.1").innerHTML = fetch('the URL')
.then(response => response.text())
.then((response) => {
    console.log(response)
})

and many other methods. I've also checked and the API request works perfectly, returning a string.

CodePudding user response:

You want the setting of the html to appear when you log the final response, eg:

fetch('the URL')
.then(response => response.text())
.then((response) => {
    console.log(response)
    document.getElementById("1.1").innerHTML = response
})

Other ways including making the whole of the response promise to be fulfilled:

const getData = async (url) => {
  const res = await fetch(url)
  const resText = await res.text()
  return resText
}
const addTextFromUrl = async (url, element) => {
  const text = await getData(url)
  element.innerHtml = text
}
addTextFromUrl('theUrl', document.getElementById("1.1"))

Generally it is a little easier to follow the async/await syntax when learning, but you should always try/catch any errors.

CodePudding user response:

Every .then call does return a new promise. So

You need to assign value in a callback or use async/await

fetch('the URL')
.then(response => response.text())
.then((response) => {
    document.getElementById("1.1").innerHTML = response
})

or do it inside an async function

async function getHtml() {
  document.getElementById("1.1").innerHTML = await fetch('the URL')
   .then(response => response.text())
}

getHtml();

W/o using then

async function getHtml() {
  const response = await fetch('the URL');

  const html - await response.text();

  document.getElementById("1.1").innerHTML = html;
}

getHtml();

  • Related