简体   繁体   English

Javascript:元素 onchange 事件异步/等待回调

[英]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() .我有两个 HTML 元素,其中一个元素在更改时必须通过名为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):以下没有(控制台中没有抛出异常,并且#elem没有更新):

<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. (function() {...})()这会调用 function。 it's like invoking a named function someFunction()这就像调用一个名为 function someFunction()

in your second example you're just creating a function without invoking it.在您的第二个示例中,您只是创建了一个 function 而不调用它。 it returns the function itself.它返回 function 本身。

  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 .第一个示例是所谓的自调用 function This is why is is wrapped in () and is followed by () to call the function immediately.这就是为什么 is 包裹在 () 中,后跟 () 以立即调用 function。

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.只需添加“const myFunc = async () => {}”并在按钮单击时调用“myFunc”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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