简体   繁体   中英

Javascript: element onchange event async/await callback

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?

(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.

The first example is what is known as a self invoking function . This is why is is wrapped in () and is followed by () to call the function immediately.

The second answer isn't working because you are not actually calling it. Simply add "const myFunc = async () => {}" and call "myFunc" on the button click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM