是否可以暂停代码直到解决承诺?



我的代码包含下面的事件侦听器。我正在尝试暂停我的代码,直到事件侦听器中的承诺(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中是不可能的(除非你想用webworker破解一些东西,但这不是你想要的(。即使await也只是语法糖,使代码看起来是程序化的,但它在引擎盖下使用了承诺。原因是javascript只运行一个线程,所以没有"其他"线程需要等待。

您可能想做的是首先启动某种"加载指示器",以向用户显示内容正在加载。然后调用你的异步东西并给它一个回调(例如 promise 的resolve函数(以将你的应用程序设置为下一个状态(即删除加载指示器并执行后续操作(。当然,您可以使用await语法使其看起来甚至听起来像"等待",但请记住,实际上只有一个线程在运行。

最新更新