简体   繁体   中英

How to get return value in my html file calling async javascript function in another file?

I have my index.html file with a simple form

Update

<form onSubmit=" App.estraiVincitore().then(value => { alert (value)}); return false;">
    <input type="submit" value="Get Winner">
    <input type="text" name="winner">    
 </form> 

I have a App.js file with an async function that works properly getting an event transaction.

estraiVincitore: async() => {
  await App.vincitoreDelContest.estrazioneVincitore().then(function (value) {
      console.log(value.logs[0].args.username);
      return value.logs[0].args.username;   //returned value to show in my index.html
       
  });

How can I get the returned valued from my JavaScript function and shows it in my index.html? Properly I would like to show it in my text area.

Thanks a lot.

How can I get the returned valued from my JavaScript function and shows it in my index.html?

By using the promise that estraiVincitore returns in JavaScript code in the index.html file. An async function returns a promise; later , that promise is settled (fulfilled with a value, or rejected with a "reason" [error]).

So for instance:

App.estraiVincitore()
.then(value => {
    document.querySelector("selector-for-your-text-area").value = value;
})
.catch(error => {
    // ...handle/report the error...
});

Re Felix's point , the purpose of async / await is to make it possible to use promises with simple logical flow constructs rather than callbacks. So:

estraiVincitore: async() => {
  const value = await App.vincitoreDelContest.estrazioneVincitore();
  console.log(value.logs[0].args.username);
  return value.logs[0].args.username;
}

Which is (basically) equivalent to this non- async function:

estraiVincitore: () => {
  return App.vincitoreDelContest.estrazioneVincitore().then(value => {
      console.log(value.logs[0].args.username);
      return value.logs[0].args.username;
  });
}

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