Redux形式转换返回承诺而不是解析值

q9yhzks0  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(128)

我尝试返回一个web3值而不是一个promise,以便调用getId方法。
我的web3的返回值尚未解析,因此仍然是一个承诺,因此我无法对其调用getId方法
任何有经验的redux用户可以指出我下面的代码有什么问题吗?谢谢
行动中. js

export const web3Loaded = (eth) => {
  const web3 = new Web3(eth);
  return async (dispatch) => {
    dispatch({
      type: WEB3_LOADED,
      connection: web3,
    });
    return web3; // it remains a promise
  };
};

在应用程序jsx中

useEffect(() => {
    const loadBlockchain = async () => {
      if (window.ethereum) {
        try {
          await window.ethereum.enable();
          const web3 = web3Loaded(window.ethereum);
          console.log("web3", web3); // it returns a promise hence I'm unable to call the getId method
          const networkId = await web3.eth.net.getId();
          console.log("networkId", networkId);
        } catch (error) {
          console.log(
            "Non-Ethereum browser detected. You should consider trying MetaMask!"
          );
        }
      }
    };
    loadBlockchain();
  }, []);
x759pob2

x759pob21#

只需在调用web3Loaded时添加一个等待即可解决此问题

useEffect(() => {
    const loadBlockchain = async () => {
      if (window.ethereum) {
        try {
          await window.ethereum.enable();
          const web3 = await web3Loaded(window.ethereum);
          console.log("web3", web3); // it returns a promise hence I'm unable to call the getId method
          const networkId = await web3.eth.net.getId();
          console.log("networkId", networkId);
        } catch (error) {
          console.log(
            "Non-Ethereum browser detected. You should consider trying MetaMask!"
          );
        }
      }
    };
    loadBlockchain();
  }, []);

相关问题