简体   繁体   English

从外部js文件调用html页面异步函数的结果

[英]Call result of async func on html page from external js file

I have async func in JS file.我在 JS 文件中有异步函数。 And a html page where i want use a result this func.还有一个 html 页面,我想在其中使用这个函数的结果。

JS File JS文件

async function Tokens_per_owner() {
  let tokens_owner = await contract.nft_tokens_for_owner({account_id: window.accountId.toString() });
  let user_tokens = [];
  
  for (let i in tokens_owner) {
      user_tokens.push(tokens_owner[i]['token_id']);
  }

  return user_tokens;
}

window.onload = async () => {
  const array_user_tokens = await Tokens_per_owner();
};

window.array_user_tokens = array_user_tokens; window.array_user_tokens = array_user_tokens;

and my html page和我的 html 页面

<script src="./wallet.js"></script>
<script type="text/javascript">
console.log(window.array_user_tokens);</script>

console.log doesnt work. console.log 不起作用。 How can i get array_user_tokens in my html page?如何在我的 html 页面中获取 array_user_tokens?

Asynchronous request, in Javascript, can be notoriously hard to understand.在 Javascript 中的异步请求是出了名的难以理解。 Your console.log does not work, since you are running it before the asynchronous request is done.您的 console.log 不起作用,因为您在异步请求完成之前运行它。 Take, for example, the following snippet.举个例子,下面的代码片段。 We have an asynchronous function that takes 5 seconds to execute.我们有一个异步 function 需要 5 秒来执行。

 const myFunction = async function() { await new Promise(resolve => { setTimeout(() => resolve(true), 5000); }); } window.onload = async () => { await myFunction(); console.log('called from function'); };
 <script> console.log('called from html'); </script>

You can see that, even if the timeout takes only 1 ms, its console.log will be run after the one from the HTML.可以看到,即使超时时间只有 1 毫秒,它的console.log也会在 HTML 之后运行。 You have the same problem.你有同样的问题。

When you want to use an async function, everything that used something from that async function, needs to be async as well.当您想使用异步 function 时,使用来自该异步 function 的所有内容也需要异步。

I'm not sure how you want to use the window.array_user_tokens array, but you should use it after the call to the async function, in the window.onLoad callback.我不确定你想如何使用window.array_user_tokens数组,但你应该在调用异步 function 之后在window.onLoad回调中使用它。

this question approach this problem very well. 这个问题很好地解决了这个问题。 I suggest you look into its anwsers.我建议你看看它的回答者。

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

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