0👍
You can’t do it this way.
fetch(url) returns a promise, meaning the function doesn’t necessarily finish before you use the return value.
You have to put the rest of your code inside the second then.
You can easily see that if you use console.log(out) under the then-catch chain, it will print the value before the console.log(‘Checkout this JSON! ‘, out), and it will log out undefined
.
- Chartjs-ChartJS Pie Chart How default just show 2 legend datas
- Chartjs-Am using Chart.js and am trying to list the attendances for the last 7 days
-1👍
Okay, let’s try this:
I replaced the fetch promise and the json promise with other promises, just for you to see the syntax. Let’s say the payload is what is returned from the fetch –
const payload = {value: "someValue"};
Promise.resolve({
json: () => Promise.resolve(payload)
})
.then(res => res.json())
.then((out) => {
var myContext = document.getElementById("myChart");
var myChartConfig = {
type: 'bar',
//this is schould be replaced by "out"
data: payload
}
var myChart = new Chart(myContext, myChartConfig);
})
.catch(err => { throw err });
As you can see, I relocated the rest of the function into the second then
, where out
has the value of the resolved promise.
You can see the working example here.
Hope this helps.