如何在JavaScript简写if-else(三元)语句中正确使用await?
问题原因
await 关键字仅可在标记了 async 的函数作用域内使用,你当前的事件监听回调是普通箭头函数,没有声明为异步函数,因此直接在内部使用 await 会触发语法错误,和三元表达式的写法本身无关。
解决方法
给事件监听的回调函数加上 async 修饰符即可,你还可以把返回空值的三元表达式替换为更简洁的逻辑与写法,更符合精简代码的需求:
//Find the tabs using the query selector document.querySelector('#main-tabs') //Add an event listener that listens for the `shown` bootstrap tab event .addEventListener('shown.bs.tab', async (e) => { // 此处为回调添加async声明 //Take the id of the tab and if the name equals "overview-tab" //then load the grid, if it doesn't then do nothing. e.target.id == "overview-tab" && await load_grid_opportunities(); });
额外优化建议
异步回调的报错不会被默认捕获,建议增加异常捕获逻辑,避免网格加载失败导致页面出现全局报错:
document.querySelector('#main-tabs') .addEventListener('shown.bs.tab', async (e) => { if (e.target.id !== "overview-tab") return; try { await load_grid_opportunities(); // 可在此处补充加载完成后的后续逻辑,例如关闭加载提示 } catch (error) { console.error('网格加载失败:', error); } });
内容的提问来源于stack exchange,提问作者Yanayaya
相关产品推荐
相关产品推荐

