我的代码包含下面的事件侦听器。我试图暂停我的代码,直到事件侦听器中的Promise(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]});
})
答案 0 :(得分:0)
否,目前无法在javascript中使用(除非您想与网络工作者一起入侵,但这不是您想要的)。甚至await
只是使代码看起来具有过程性的语法糖,但它在幕后使用了promises。原因是javascript仅运行一个线程,因此没有“其他”线程需要等待。
您可能想要做的是首先踢入某种“装载指示器”,以向用户显示物料正在装载。然后调用您的异步内容并为其进行回调(例如promise的resolve
函数),以将您的应用设置为下一个状态(即删除加载指示器并进行后续操作)。当然,您可以使用await
语法使它看起来甚至听起来像“正在等待”,但是请记住,实际上只有一个线程在运行。