What is the appropriate utilization of the await keyword within concise if-else statements in JavaScript?

Along with transitioning away from jQuery, my main focus is to make my code more efficient. In large scale enterprise applications, the excessive use of jQuery and JavaScript can become problematic.

I have decided to switch back to vanilla JavaScript for better development practices. Although I rely on jQuery to make KendoUI work in my applications, I aim to keep the rest of my code clean and streamlined by using shorthand and asynchronous techniques whenever appropriate.

The JavaScript statement I want to execute should accomplish the following objectives:

  • Locate the tabs container
  • Attach an event listener to monitor the tabs Id when it's event is triggered as shown
  • Asynchronously load a KendoUI grid while waiting for completion

So, to achieve this using concise vanilla JavaScript, I implemented 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) => {

        //Extract the id of the tab and if its name equals "overview-tab", 
        //then load the grid; otherwise, do nothing.
        (e.target.id == "overview-tab") ? load_grid_opportunities() : null;

    });

Now, let's move forward and create the asynchronous function responsible for loading the grid. I created the async function called load_grid_opportunities, followed by standard KendoUI jQuery widget binding.

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

At this point, I am stuck wondering how to properly await the async function in my if/else statement. My initial instinct was to use the await keyword inline like this:

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

However, this approach did not work as it resulted in an unexpected argument error. I also attempted using parentheses to encapsulate the request, but that did not resolve the issue either.

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

So, I am now puzzled about how to correctly utilize await with my function. Any suggestions would be greatly appreciated!

Answer №1

To optimize the performance of your function, it is recommended that you ensure it returns a promise. Take a look at this code snippet for reference:

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

// You may now invoke your function

async function doSomething()
{

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

display active users in the chatroom sidebar

Currently, I am working on developing a chatroom application but have encountered an issue with displaying online and offline users. I have implemented a session for tracking online users - when a user logs in, the session is updated in the database to ind ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

Error encountered when URLSearchParams attempts to add an array

Hi, I'm encountering a problem when attempting to send an array using URLSearchParams. Here is the code snippet in question: const worker = async(endpoint, method, parameters) => { let body; if (typeof parameters === 'object' &am ...

error 404 when sending a xhr request in node and react js

I am currently developing a basic login page in React that needs to connect to a database through an AJAX call to a Node.js file. Here is the Node.js code I have implemented: var express=require('express'); var app=express(); var db=require(&ap ...

Puppeteer encountered an error when trying to evaluate the script: ReferenceError: TABLE_ROW_SELECTOR was not defined

https://i.stack.imgur.com/PJYUf.jpg Recently, I started exploring pupeteer and node while using vscode. My goal is to log into a website and scrape a table. So far, this is what I have: (async () => { const browser = await puppeteer.launch({ headle ...

Removing Form Fields Utilizing Javascript

Is it possible to create a unique function in Javascript that automatically removes a form field if it remains unfilled? <form id="myform"> <label for="q1" id="q1label">question 1</label> <input type="text" id="q1" name="q1"/> < ...

Tips for positioning two elements side by side on a small screen using the Bootstrap framework

Greetings! As a beginner, I must apologize for the lack of finesse in my code. Currently, I am facing an issue with the positioning of my name (Tristen Roth) and the navbar-toggler-icon on xs viewports. They are appearing on separate lines vertically, lea ...

Show HTML content from different domains within a navigation tab's content area

I am in need of showing content from a different domain on my webpage within a navigation tab. I have followed the example given in the link below: Loading cross domain endpoint with jQuery AJAX This is how my HTML code looks like: <section class=" ...

Show a variety of pictures using React

Is it possible to repeat an image (e.g. photo.jpg) n times in Reactjs using a provided value for n in props? If yes, how can this be achieved? function Card(props) { for (let i = 0; i < props.rating; i++) { <img className="star" src ...

React hook form submit not being triggered

import React, { useState } from "react"; import FileBase64 from "react-file-base64"; import { useDispatch } from "react-redux"; import { makeStyles } from "@material-ui/core/styles"; import { TextField, Select, Input ...

Utilizing the componentDidUpdate method to update the state within the component

I have a scenario where two components are enclosed in a container. One component is retrieving the Id of a publication, while the other is fetching the issue date related to that specific publicationId. When I retrieve an Id, let’s say 100, it successf ...

The Antd table documentation mentions that rowKey is expected to be unique, even though it appears they are already

Having trouble with a React code issue. I have a list of products, each with an array of 7 items that contain 40 different data points. This data is used as the source for a table. {label : someStringLabel, key: someUniqueKey, attribute1: someInt,..., at ...

Is there a way to stop a for-in loop within a nested forEach function in JavaScript?

I am facing a situation with nested loops for (var key in params) { if (Array.isArray(params[key])) { params[key].every(function(item) { let value = something(item.start, item.end); if (value === item.start || value == item.end) { ...

Finding out if an array is empty or not in Reactjs: A Quick Guide

I am currently working with Reactjs and Nextjs. I am using axios to fetch data, and I need a way to determine if the array (students.data) is empty before running a map or loop. How can I achieve this? Here is the code snippet I am working with: const [stu ...

Sorting tables with jQuery UI sortable() and rowspan功能

Can jQuery UI's sortable() be configured to sort rows based on their "containing" element only? I have a table with rowspanned cells that should only be sorted within their respective spanned columns. var $sortable = $('.nested-sortable tbody&ap ...

Experiencing ERR_TOO_MANY_REDIRECTS while using Next.js with Vercel and a Custom Domain through Cloudflare

I'm having trouble getting my Next.js project set up on Vercel with a custom domain managed through Cloudflare. Despite configuring the DNS and SSL settings correctly, I keep seeing a net::ERR_TOO_MANY_REDIRECTS error when trying to access my site at ...

Is there a way to dynamically compute the height of rows in a VariableSizeList based on their index?

Is there a method to dynamically calculate the height of rows in React using the react-window library? Since it's uncertain whether all rows will have the same size, I find myself needing to utilize VariableSizeList. However, I'm wondering if the ...

Something is amiss with the PHP email validation functionality

I have been facing issues with the functionality of my form that uses radio buttons to display textboxes. I implemented a PHP script for email validation and redirection upon completion, but it doesn't seem to be functioning correctly. The error messa ...

unable to decipher a JSON file obtained from Instagram

I have been working on a project that involves parsing a JSON file obtained from the Instagram API. However, I am facing an issue where I can parse the data but I cannot read it properly in my code: <!DOCTYPE html> <html> <head> <meta ...

Error with WooCommerce checkout causing input values to disappear upon clicking or submitting

I am facing an issue where I need to set #billing-postcode to a specific value using a JS script. When I input jQuery('#billing-postcode').val('2222') on the checkout page, the input displays the value 2222 with the Postcode label abov ...