我的代码包含下面的事件监听器。我试图暂停我的代码,直到事件监听器中的承诺(window.ethereum.enable())被解决。我应该如何去做这件事?
window.addEventListener('click', async () => {
if (window.ethereum) {
this.web3 = new Web3(window.ethereum);
try {
await window.ethereum.enable();
alert("if:" + this.web3)
return this.web3;
} catch(err){}
}
else if (window.web3) {
this.web3 = window.web3;
return this.web3;
}
else {
const provider = new Web3.providers.HttpProvider('wss://ropsten.infura.io/ws/v3/PROJECT-ID');
this.web3 = new Web3(provider);
return this.web3;
}
this.web3.eth.getAccounts().then(accounts => { this.state.account = accounts[0]});
})
不,目前在javascript中是不可能的(除非你想用网络工作者来破解一些东西,但这不是你在这里想要的)。甚至 await
只是语法上的糖,使代码看起来是程序化的,但它在下面使用了承诺。原因是javascript只运行一个线程,所以没有 "其他 "线程需要等待。
你可能想做的是首先启动某种 "加载指示器",向用户显示东西正在加载。然后调用你的async东西,并给它一个回调(如 resolve
的函数)来将你的应用程序设置为下一个状态(即删除加载指示器,并做任何后续工作)。当然,你也可以使用 await
语法,使它看起来甚至听起来像 "等待",但请记住,实际上只有一个线程在运行。