JavaScript 'await' throws error 'then is not defined'

Just starting out with async programming and I've noticed a common issue in similar threads - the problem of not returning anything. However, in my case, I am facing a different error message 'Cannot read property 'then' of undefined'.

function getWorkItems(iterationPath, projectId) {

    var queryClient = VSS_Service.getCollectionClient(TFS_Wit_QueryAPI.WorkItemTrackingHttpClient);
    var query = { query: "SELECT [System.Id] FROM WorkItem WHERE [System.IterationPath] = '" + iterationPath + "'" };
    var resultOfQuery;

    queryClient.queryByWiql(query, projectId).then(

        function (resultOfQuery) {
            return new Promise((resolve, reject) => {
                resolve(resultOfQuery);
                console.log("Debug: " + JSON.stringify(resultOfQuery));
            })
            VSS.notifyLoadSucceeded();

        });
}

Although the debug message is printed successfully and data is fetched from the server, an error occurs when calling it from another location.

let bar;

getWorkItems(counter.path, projectId).then ( res => {
    bar = res;
    console.log("Debug: should be output of query " + JSON.stringify(bar));
})

The error message 'Cannot read property 'then' of undefined' pops up in this scenario.

Answer №1

When looking at the code for getWorkItems, it's important to note that there is no explicit return statement, which means it will implicitly return undefined. Additionally, as

queryClient.queryByWiql(query, projectId)
is already returning a promise, there is no need to create another promise. You can simply streamline the function like this:

function retrieveWorkItems(iterationPath, projectId)
{
  var queryClient = VSS_Service.getCollectionClient(TFS_Wit_QueryAPI.WorkItemTrackingHttpClient);
  var query = { query: "SELECT [System.Id] FROM WorkItem WHERE [System.IterationPath] = '" + iterationPath + "'" };
  return queryClient.queryByWiql(query, projectId);
}

If you wish to include a log statement and notifyLoadSucceeded within the function, you can do so without creating an additional promise. When inside a .then callback, you just need to return the desired value for the promise resolution:

function retrieveWorkItems(iterationPath, projectId)
{
  var queryClient = VSS_Service.getCollectionClient(TFS_Wit_QueryAPI.WorkItemTrackingHttpClient);
  var query = { query: "SELECT [System.Id] FROM WorkItem WHERE [System.IterationPath] = '" + iterationPath + "'" };
  return queryClient.queryByWiql(query, projectId)
    .then(function(queryResult) {
      console.log("Debug: " + JSON.stringify(queryResult));
      VSS.notifyLoadSucceeded();
      return queryResult;
    });
}

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

Could someone please assist me with an issue I am experiencing with an AJAX GET request?

My code is not fetching any data for me. Below is the code snippet: <script type="text/javascript"> function matriculaFn(mat) { $.ajax({ method: 'GET', url:'My url API, async: true, crossDomain: false, contentType: 'application/j ...

Guide on invoking a function in a PHP file using jQuery's load method

I am having trouble displaying the data retrieved from the database. There is a function called "getComments(page)" in the getComments.php file, where 'page' is an integer parameter corresponding to the chosen database. I need to call this functi ...

What is the best way to identify the type of an element using AngularJS?

Is it possible to use ng-model to identify the type of an element? For example: How can we determine if a specific element is a dropdown or a checkbox? HTML Code Snippet <select multiple ng-model='p.color'> <option value="red">Re ...

Selenium Python Slider Button Element Visibility Issue

Currently, I am developing a parser to automate the process of clicking buttons on a website. However, I am encountering difficulties in clicking two specific buttons. The buttons I am aiming to click are "Elija el imports a financiar" and "Elija la mensu ...

Troubleshooting: CSS Styles not loading when passed as property in MUI withStyles

I am currently working on a react component that has a specific style defined as shown below: const StyledInnerItem = withStyles((theme) => ({ bgColor: { backgroundColor: (props) => { console.log('styledInnerItem color: ', props ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Utilizing Material UI's (MUI) date picker in conjunction with react-hook-form offers a

I'm currently developing a form with a date field utilizing MUI and react-hook-form for validation. I have experimented with two different methods of rendering the field, but when I try to submit the form, the expected value is not being returned: Me ...

Using jQuery, target the specific elements that have certain data attributes assigned to them

Is there a way to target elements with a specific data attribute and a unique class using jQuery? For instance, I want to select these elements: <div data-roomid="55" data-status="NoData"></div> <div data-roomid="55" data-status="Open"> ...

Selecting radio buttons across multiple div classes

I've been struggling to programmatically select specific radio buttons on a webpage. My goal is to automatically choose the second option in each group of radio buttons, but I'm getting lost in the syntax. Unlike most examples I've found on ...

Is there a way to verify the authenticity of a survey depending on the types of form elements used

Creating a form in PHP with various dynamic form elements like radio buttons, text fields, and dropdowns. Seeking to validate this form using JQuery based on the question type, which is identified by the names q1, q2, etc. $(function(){ if ($(&apo ...

Prevent user input in Vue.js until the value has been modified

Need help handling initial input values: <input type="text" v-model="name" ref="input" /> <button type="submit" :disabled="$refs.input.defaultValue == $refs.input.value">Submit</button> Encountering an error with the disabled binding: C ...

Adding an active class to a large image when a thumbnail image is clicked can enhance user experience and

I've created a photo gallery using jquery. Currently, when I click on "next", the image changes based on the index. However, I also want to be able to click on the thumbnails (small images) and display the larger image according to that specific inde ...

Generating a collection of items within a JavaScript object

Struggling with sending a json object to a java API backend that requires an Object containing a list of objects. Wondering if it's possible to create a list of objects inside a javascript Object. While I know we can create an "Array" of objects with ...

Issue with Javascript Date and Time Validation

My application includes code that is supposed to display HTML pages based on today's date and the time of day (morning, afternoon, or evening). However, it seems like there is an issue with how the time is being checked. Currently, at 2:53pm, only the ...

A script page in Wordpress generates a numerical value in the URL

I created a script named search.php which utilizes various search engines APIs to display search results. From this file, I have developed a Page template and incorporated the simplePagination plugin The issue arises when I click on a page within the pag ...

I prefer to avoid generating the document structure while parsing with JSOUP

Utilizing the Jsoup API to parse a section of HTML using the Jsoup.parse() method. However, during parsing, it includes the document structure in the HTML content. For Instance: <p><a href="some link">some link data</a> Some paragraph c ...

Guide to importing images (.svg, .png) into a React component

I'm currently facing an issue trying to upload an image file in one of my React components using webpack. My project is already set up with web pack. Below is the code snippet for the component: import Diamond from '../../assets/linux_logo.jpg& ...

Struggling to implement dynamic background color changes with react hooks and setTimeout

I am struggling to update the colors of 3 HTML divs dynamically, but unfortunately the code below doesn't seem to be effective. function App() { const [redBgColor, setRedBgColor] = useState(null) const [yellowBgColor, setYellowBgColor] = useState( ...

Refresh the page with cleared cache using window.location.reload

Is there a way to reload a page using JavaScript and still clear the cache, ensuring that the refreshed page shows the latest content from the server? It seems that other browsers are not displaying the most up-to-date versions of the content. Anyone have ...

A guide on merging existing data with fresh data in React and showcasing it simultaneously

As a newcomer to Reactjs, I am facing the following issue: I am trying to fetch and display new data as I scroll down Every time I scroll down, I fetch the data and save it in Redux. However, due to pagination, only 10 items are shown and not added to th ...