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

What is the solution for the error "Build error occurred ReferenceError: self is not defined" when building a NextJs application?

pages/components/moru-sdk.js // https://libraries.io/npm/moru-web-sdk import { MoruCheckout } from "moru-web-sdk"; function MoruService() { const options = { access_key: "test_9425294388834bdface7d1b58fd538bf67627d9408fe4f258982 ...

What is the best way to show the user profile on a Forum?

I am struggling to figure out how to display the username of a user on my forum page. I currently only have access to the user's ID and need help in extracting their name instead. It seems that I lack knowledge about mongoose and could really benefit ...

Angular 2 signal sender

I have a specific class definition for my Project: export class Project { $key: string; file: File; name: string; title: string; cat: string; url: string; progress: number; createdAt: Date = new Date(); constructor(file: File) { th ...

What is the best way to shorten text in React/CSS or Material UI based on the line height multiples?

I'm facing an issue with creating a Material UI card that contains text. My goal is to set a fixed height for the card and truncate the text if it exceeds 3 lines. Can anyone suggest the best approach to achieve this? Here's the code snippet I&a ...

What is the best way to implement onChange for multiple form fields in Reactjs?

Can anyone help me troubleshoot my form? I'm having issues with typing into the fields and nothing happens when I try. Initially, whatever text I input would show up in all the fields simultaneously, but after making some changes, it stopped working ...

Obtaining JSON information within the AngularJS Scope

I am delving into the world of AngularJS for the first time and trying to understand it by following this example: http://jsfiddle.net/SAWsA/11/ After successfully acquiring data in JSON format, I encountered no issues. Here is a snippet of the JSON data: ...

Is there a way to prevent the Pace js plugin from running on page load, but still have it execute during Ajax requests only?

I have successfully implemented the jquery pace plugin with a progress bar theme. Everything is working well, but I am looking to make it run only on ajax requests. I have tried various solutions found through research, but haven't had any luck. Belo ...

Installing Yarn causes the download of an unconventional directory

Currently, I am facing an issue while trying to install yarn on my Macbook Pro (2017). The installation process seems to be downloading a folder called /react-praktis/ instead of completing successfully. Below is a screenshot for reference: https://i.stac ...

Encountering a script error when upgrading to rc4 in Angular 2

After attempting to update my Angular 2 version to 2.0.0.rc.4, I encountered a script error following npm install and npm start. Please see my package.json file below "dependencies": { "@angular/common": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", ...

Encountered an error when attempting to submit with Node.js and Express.js connected to MySql - "Cannot POST /login

I am currently working on creating a basic login page using node.js with the express.js and mysql packages. The goal is to redirect users to the layout.html page if their username and password exist in the mysql database. For this project, I have set up a ...

Tips for creating a fixed element with ScrollTrigger and GSAP

How can I prevent the right div from jumping on top of the left div when using a scroll trigger to make the left div's position fixed? gsap.registerPlugin(ScrollTrigger); const tlfour = gsap.timeline({ scrollTrigger: { trigger: ".ma ...

Top method for detecting errors in Models? (Node.js + Sequelize)

Looking for a straightforward method to catch errors in an API using Node.js and Sequelize models? Take a look at this code snippet which utilizes async-await: const router = express.Router() const { Operations } = require('../models') router.po ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

What is the best way to trigger an onclick event for an input element with a type of "image"?

In the code I'm working on, there's an input of type "Image". <div class="icon" id="button_dictionary"> <form> <input class="buttonDictionary" type="image" src="icone_dicionario.jpg" value="" id="inputDictionary"> ...

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

Implementing asynchronous file reading with module.exports in Node.js

Apologies in advance for what may seem like a basic question, but I'm delving into the inner workings of node and need help with a particular issue: I am trying to send an object or file from fs.readFile using require and module.exports. So far, this ...

Error occurred when sending form data while uploading a file

Upon trying to upload a file using the formData.append(key, value);, an error message is displayed in the value section: The argument of type 'unknown' cannot be assigned to a parameter of type 'string | Blob'. Type '{}' is ...

Tips for incorporating an anchor tag within an img tag in HTML?

Is it possible to add an anchor tag inside an img tag in HTML? <img src="img.jpg" alt="no img" /> I want to include the following inside the img tag: <a onclick="retake();" > Retake </a> The goal is to allow users to retake a photo by ...

div maintain aspect ratio while scaling

My current layout is structured like this: HTML <div id="container"> <div id="zoomBox"> <div class="box"></div> <div class="box"></div> <div class= ...