I'm not only making a transition away from jQuery but I am also trying to make my code a lot leaner. As I work on large scale enterprise applications the amount of jQuery and JavaScript that is being used can reach crisis point.
I want to start working in a better way and using vanilla JavaScript again. I build applications using the likes of KendoUI and it hinges on jQuery to make it work. That said, I want to keep the rest of my code as vanilla JavaScript, shorthanded and efficient (asynchronous where appropriate).
I'm trying to achieve the following goals with a JavaScript statement of mine
- Find the tabs container
- Bind an event listener to check the tabs Id when it's event is
shown
- Load a KendoUI grid asynchronously awaiting it
So, to achieve this in shorthand vanilla JavaScript I did the following.
//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;
});
Ok, so from here I went and created my asynchronous function that loads my grid. I created an async function called load_grid_opportunities
and then we encounter generic KendoUI jQuery based widget binding.
const load_grid_opportunities = async () => {
$('#grid_opportunities').kendoGrid({
//shortened for brevity
});
}
This is where I have gotten to because now I'm wondering, how do I await this async function in my if/else statement? My first instinct was to simply call await
inline like this:
(e.target.id == "overview-tab") ? await load_grid_opportunities() : null;
However, this didn't work as it's an unexpected argument. I then tried to use parenthesis to encapsulate the request but that didn't work either.
(e.target.id == "overview-tab") ? (await load_grid_opportunities()) : null;
So, how on earth can I await my function?
CodePudding user response:
To await your function your function must return promise, please see the code below.
function load_grid_opportunities() {
return new Promise((resolve, reject) => {
$('#grid_opportunities').kendoGrid({
//shortened for brevity
resolve();
});
});
}
// Now you can call your function
function async doSomething()
{
if (e.target.id == "overview-tab")
{
await load_grid_opportunities()
}
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>