I have async func in JS file. And a html page where i want use a result this func.
JS File
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;
and my html page
<script src="./wallet.js"></script>
<script type="text/javascript">
console.log(window.array_user_tokens);</script>
console.log doesnt work. How can i get array_user_tokens in my html page?
Asynchronous request, in Javascript, can be notoriously hard to understand. Your console.log does not work, since you are running it before the asynchronous request is done. Take, for example, the following snippet. We have an asynchronous function that takes 5 seconds to execute.
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. 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.
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.
this question approach this problem very well. I suggest you look into its anwsers.