'Async JS : The console log displays the data as text but the HTML DIV renders [Promise Object]
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>
Solution 1:[1]
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);
}
};
Solution 2:[2]
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;
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yassine Lhb |
| Solution 2 | I.Orlovsky |
