Within a timer
called javascript function
I need update a UI using several json API calls.
It's an energy meter which stores the actual consumed phase power in 3 different registers. Except for negative values (energy by solar panels), this returned energy is stored in 3 other registers (as a positive value). If
phase power is 0, I need need to fetch the alternate phase power register.
Loop 3 times
Fetch A at api1
If A=0 Then
Fetch A at api2
Display A
Display min(A)
Display max(A)
Display trend
Even more display stuff I don't want to duplicate
I manage to fetch the value, however can't get the alternative fetched value to survive below the fetch
block. Display A = 0 when fetching api2 (which returns not 0).
I tried async
and await
, like Javascript - How to use fetch inside a for loop and wait for results. Thus change 2 lines in the code below:
async function update()
…
await fetch(APIGW+"v1/sm/fields/power_returned_l"+myPhase)
That results in:
Uncaught SyntaxError: await is only valid in async functions and async generators
Uncaught ReferenceError: update is not defined
How to make the bottom document.getElementById
(and loads of UI stuff below) to wait for the 2nd level (not the 2nd loop) fetch when this if (nvKW == 0 )
block is executed?
function update()
{
var phase;
for( let phase = 1 ; phase <= PHASES ; phase++ )
{
fetch(APIGW+"v1/sm/fields/power_delivered_l"+phase)
.then(response => response.json())
.then(json =>
{
for( let j in json.fields ){
if (json.fields[j].name.startsWith("power_delivered_l"))
{
myPhase = Number(json.fields[j].name.replace('power_delivered_l',''));
let nvKW=Number(json.fields[j].value)
if (nvKW == 0 ) // check if power is generated
{
fetch(APIGW+"v1/sm/fields/power_returned_l"+myPhase)
.then(response => response.json())
.then(json2 =>
{
for( let jr in json2.fields ){
if (json2.fields[jr].name.startsWith("power_returned_l"))
{
let nvKW=-1*Number(json2.fields[jr].value)
console.log(json2.fields[jr].name+" = "+ nvKW.toString()) // here nvKW contains a value
}
}
}
);
}
console.log("nvKW = "+ nvKW.toString()) // 1st level fetch = 0 and 2nd level fetch != 0 then nvKW is still 0 here, where I need the value from the 2nd level fetch
document.getElementById(json.fields[j].name).innerHTML = nvKW.toFixed(1);
// a lot more ui stuff is done below