Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: element onchange event async/await callback

Tags:

javascript

I hope this question is not duplicated. I have two HTML elements, one which when it's changed must populate the value of another via an async method named foo().

The following code works:

<input type="text" id="elem">
<input type="file" onchange="
    (async ()=>{
       document.getElementById('elem').value = await foo(this);
    })()
">

The following one doesn't (no exception is thrown in console, and #elem is not updated):

<input type="text" id="elem">
<input type="file" onchange="
   async ()=>{
      document.getElementById('elem').value = await foo(this);
   }
">

Why the first example works and the second doesn't?

like image 419
user8555937 Avatar asked Nov 01 '25 06:11

user8555937


1 Answers

(function() {...})() This invokes the function. it's like invoking a named function someFunction()

in your second example you're just creating a function without invoking it. it returns the function itself.

  1. invoking:
onchange='someFn()'; // calls function
  1. without invoking
onchange='someFn'; // returns function.
like image 182
fedesc Avatar answered Nov 02 '25 20:11

fedesc