C
C
Cpa2018-03-19 09:47:38
JavaScript
Cpa, 2018-03-19 09:47:38

Why doesn't Return JS work?

Why is there no access to the variable ?

<script>

navigator.getBattery().then(function(battery) {    
  level = battery.level * 100;
  return level;
});
alert(level);

</script>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2018-03-19
@Cpa

Because you don't know how return works and what asynchronous events are.
At the moment when you call alert, the promise has not yet been fulfilled.

C
Coder321, 2018-03-19
@Coder321

async function getBattery() {
try {
const battery = await navigator.getBattery();
level = battery level * 100;
alert(level);
} catch (error) {
console.log(error);
};
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question