如何在 shorthand if else Javascript 语句中正确使用 await?

How do I correctly use await inside of shorthand if else Javascript statements?

我不仅要从 jQuery 过渡,而且我还试图使我的代码更精简。当我处理大型企业应用程序时,jQuery 和 JavaScript 的使用量可能会达到危机点。

我想以更好的方式开始工作并再次使用原版 JavaScript。我使用 KendoUI 之类的工具构建应用程序,它依赖于 jQuery 才能正常工作。也就是说,我想将我的其余代码保持为香草 JavaScript、shorthanded 和高效(在适当的情况下异步)。

我正在尝试通过我的 JavaScript 声明实现以下目标

因此,为了在 shorthand vanilla JavaScript 中实现这一点,我做了以下操作。

//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', (e) => {

        //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") ? load_grid_opportunities() : null;

    });

好的,从这里开始我创建了加载网格的异步函数。我创建了一个名为 load_grid_opportunities 的异步函数,然后我们遇到了基于通用 KendoUI jQuery 的小部件绑定。

const load_grid_opportunities = async () => {    
    $('#grid_opportunities').kendoGrid({
       //shortened for brevity
    });
}

我已经到了这里,因为现在我想知道,如何在我的 if/else 语句中等待这个异步函数?我的第一直觉是像这样简单地调用 await 内联:

(e.target.id == "overview-tab") ? await load_grid_opportunities() : null;

但是,这没有用,因为这是一个意想不到的论点。然后我尝试使用括号来封装请求,但也没有用。

(e.target.id == "overview-tab") ? (await load_grid_opportunities()) : null;

那么,我究竟该如何等待我的函数?

要等待您的功能,您的功能必须 return 承诺,请参阅下面的代码。

function load_grid_opportunities() {
    return new Promise((resolve, reject) => {
        $('#grid_opportunities').kendoGrid({
            //shortened for brevity
        });
        resolve();
    });
}

// Now you can call your function

async function doSomething()
{

if (e.target.id == "overview-tab") 
{
    await load_grid_opportunities();
}
}