I have a dynamic resultArray numbers.The console.log(data) shows the data text I want from the API. But the div in the HTML returns a [Object Promise] .
let resultArray = ['6']
const getUrl = (num) => `http://numbersapi.com/${num}`;
const getFacts = async (num) => {
try {
const resp = await fetch(getUrl(num));
const data = await resp.text();
console.log(data);
return data;
} catch (error) {
console.log(error);
}
};
let theQuote = document.getElementById("quote");
theQuote.textContent = getFacts(resultArray); // [object promise]
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body class="main">
<div id="quote"></div>
</body>
</html>
I don't sure but it may work for you.
(async () => {
let theQuote = document.getElementById("quote");
theQuote.textContent = await getFacts(resultArray);
})();
cuz your function getFacts() return a promise and you need to resolve it when use it , try to render data inside the function to avoid this
let theQuote = document.getElementById("quote");
let resultArray = ['6']
const getUrl = (num) => `http://numbersapi.com/${num}`;
const getFacts = async (num) => {
try {
const resp = await fetch(getUrl(num));
const data = await resp.text();
console.log(data);
theQuote.textContent = data;
} catch (error) {
console.log(error);
}
};
Basically you just need to wait until the promise from getFacts gets resolved. You can achieve that by using then method of the promise like below:
getFacts(resultArray).then((facts) => {
let theQuote = document.getElementById("quote");
theQuote.textContent = facts;
})