Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

asynchronous - JavaScript Async await sequential is not working, it's not waiting on the response

I'm trying to write an async sequantial function, but it looks like the next line of code will not wait till the first one is done. The problem is inside 'loadContract' function. This is the full code:

import contract from "../assets/static/build/contracts/PolarBetV4.json";
let web3 = new Web3(Web3.givenProvider);

const contractABI = () => {
  const abi = contract.abi;
  return abi;
};

const startWeb3 = async () => {
  if (window.ethereum) {
    window.web3 = new Web3(window.ethereum);
    window.ethereum.enable();
  } else {
    window.alert("Metamask not detected!");
  }
};

const loadContract = async () => {
  try {
    const address = await web3.eth.ens.getAddress("polarbet.eth");
    console.log(address);

    const result = await new window.web3.eth.Contract(contractABI(),address);
    return result;
  } catch (e) {
    console.log(e);
  }
};

export const LoadWeb3 = async () => {
  await startWeb3();
  window.contract = await loadContract();
};

If I change 'address' to the string it should be, like:


    const result = await new window.web3.eth.Contract(contractABI(), '0xc980207f705242EaKasedkDb2b');

It works. I already checked the output of 'address' using the console log. And it's the same string. But it looks like it is not waiting on the response and this line is already triggered with the promise. So not sure how I can solve this?

question from:https://stackoverflow.com/questions/65835233/javascript-async-await-sequential-is-not-working-its-not-waiting-on-the-respon

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your loadContract function is asynchronous. Async functions always return a promise. In this case, the function returns a (pending) promise that eventually resolves to the value of your result variable.

This happens immediately and is the intended behaviour of async functions. If you're still unsure, I suggest you read up on them in the MDN docs.

If you want your code to wait until window.contract is resolved, you should await your LoadWeb3 fn.

e.g.:

await LoadWeb3();

doSomethingWithTheContract(window.contract);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...