如何使用JavaScript异步等待从MetaMask获取链ID



如何从异步等待函数中获取结果值?我正在尝试在MetaMask中获取当前链ID,我得到了函数的返回对象。我期望0x4,但在函数之外无法访问它。

let account;
let currentChain;
const switchNetwork = async () => {
currentChain = await ethereum.request({ method: 'eth_chainId' });
console.log(currentChain + ' <- currentChain'); //for debug
return currentChain; //tried
}
let fromCheck = switchNetwork();
console.log(fromCheck + ' <- fromCheck'); //for debug, expecting `0x4`

结果:

[object Promise] <- fromCheck
0x4 <- currentChain

对象看起来像这样:

Promise {<pending>}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: "0x4"
0x4 <- currentChain

为了从promise(异步函数的返回类型(中获取值,必须使用.then(value => { ... })await

在您的具体情况下,这看起来像:

let fromCheck = await switchNetwork();
console.log(fromCheck + ' <- fromCheck');
// or
switchNetwork()
.then(val => {
console.log(val + ' <- fromCheck');
});

最新更新