JavaScript doesn't pause for the data to come back, resulting in an undefined value

When I call the function "classTableData" on a button click, my allData variable becomes undefined. The problem seems to be that it processes the next line of code without waiting for the results, causing allData to remain empty. Can anyone provide some assistance with this issue?

function classTableData(){
     loadStudentPDFData().then(function (results) {
                  studentPDFData = results.pdfData;
                });
        var allData = studentPDFData;
        $log.log("AllData"+allData.length);

    }

function loadStudentPDFData() {
  var deferred = q.defer();
   var core5PDFData=angular.copy(core5InstructionPlanner);
       core5PDFData.loadPDFSection('all', function() {
     deferred.resolve({pdfData:core5PDFData.dataSource('all').data()});
      });
    return deferred.promise;
  }

Answer №1

loadStudentPDFData function will return a promise.

Once the promise is resolved, it will return the object

{pdfData:core5PDFData.dataSource('all').data()}
.

It's important to note that placing

studentPDFData = results.pdfData;
inside the resolve callback is crucial to avoid issues that may arise due to asynchronous nature of JavaScript.

    var allData = studentPDFData;
    $log.log("AllData"+allData.length);

When these two lines are outside the callback, there's a risk of null being logged because studentPDFData might be undefined at that point.

To ensure proper execution, move these lines inside the callback as shown below:

 loadStudentPDFData().then(function (results) {
      studentPDFData = results.pdfData;
      var allData = studentPDFData;//you don't need this variable
      $log.log("AllData"+allData.length);
 });

JavaScript utilizes Promises for handling asynchronous operations effectively. Promises allow actions to be completed based on delayed results, such as those from database calls or HTTP requests.

For further information on promises, you can refer to this resource, and for details about the q library, visit this link.

Answer №2

Execute the task inside .then()

fetchStudentFiles()
.then(function (response) {
  $log.log("Total files: " + response.fileList.length);
  return response.fileList;
});

If another .then() is attached to classListData, then return the result of fetchStudentFiles() from the classListData() function

function classListData() {
  return fetchStudentFiles()
         .then(function (response) {
           $log.log("Total files: " + response.fileList.length);
           return response.fileList;
         });
}

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

Changes to a key value are not reflected in the array of objects

When making changes to input fields within an array of records that include Date and Text fields in a table, the data is not updating as expected. I am encountering issues where changing the Date input results in undefined Text values, and vice versa. My g ...

What is the best way to implement a subquery using EXISTS in Knex?

I'm currently facing challenges while constructing a query using knex, specifically when it comes to incorporating the 'WHERE' clause with the condition EXISTS (SELECT * FROM caregiver_patient WHERE patient_id IN (0,1)). Below is the origin ...

Using autocompletion in AngularJS by integrating with Mongoose to retrieve data

Hello everyone , I'm currently exploring the Autocomplete feature in AngularJS that retrieves data from mongoose. I came across an example like this one on Stack Overflow: https://stackoverflow.com/questions/18460374/angularjs-autocomplete-from-http ...

Storing the .NET Framework viewmodel in its own individual Javascript file

I have a question about structuring my design for SoC (Separation of Concerns). I currently have the following files: testController.cs testViewModel.cs testView.cshtml testScript.js Currently, I generate data in the controller, populate the testViewMod ...

Group records in MongoDB by either (id1, id2) or (id2, id1)

Creating a messaging system with MongoDB, I have designed the message schema as follows: Message Schema: { senderId: ObjectId, receiverId: ObjectId createdAt: Date } My goal is to showcase all message exchanges between a user and other users ...

Encountering difficulties displaying navigation interface with react native navigation's stack navigator

I am trying to implement a custom side navigation bar in React Navigation without using drawerNavigator. I have fixed the side nav bar and bottom bar in app.js so that they appear on all screens. The main content area should change based on button clicks o ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

What causes functions operating on mapped objects with computed keys to not correctly infer types?

If you are seeking a way to convert the keys of one object, represented as string literals, into slightly modified keys for another expected object in Typescript using template string literals, then I can help. In my version 4.9.5 implementation, I also ma ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...

The display of temporary headers - Nodemailer - AJAX

I keep receiving a warning in the request header that says: Provisional headers are shown. I'm struggling to identify the root cause of this issue. This warning prevents the readyState from changing and my callbacks on the eventhandler onreadystatecha ...

Unable to select an option in AngularJs using ng-repeat

How can I preselect an option in a select element rendered by ng-repeat? <body ng-app ng-controller="AppCtrl"> <div>Chosen leverage: {{openAccount.leverage}}</div> <select class="form-control" name="leverage" ng-model="openAcc ...

Retrieve error message from 400 error in AngularJS and WebAPI

Why am I having trouble reading the error message in AngularJS from this code snippet? ModelState.AddModelError("field", "error"); return BadRequest(ModelState); Alternatively, return BadRequest("error message"); return Content(System.Net.HttpStatusCod ...

The program is designed to only allow up to two images to be wrapped

I'm struggling with a short jQuery program that I need help with. The problem is, I can't seem to get it to wrap more than two images in the same row. My goal is to create a website that side-scrolls, and I thought this approach would be the simp ...

Trouble connecting JavaScript to Node application for proper functionality

After setting up Node/Express/EJS, I am now trying to include js files, but my alert("working"); is not working as expected. Quite ironic, isn't it? The main objective is to load learnJs.js in the browser and trigger the alert so that I can confirm e ...

The issue of jQuery, Ajax, and MVC6 parameters becoming null after an Ajax request has been identified

Hello everyone, I am a beginner in asp.net core, c# and MVC 6. Currently, I am facing an issue with sending data over ajax to my controller. function sendAjaxData() { $.ajax({ url: "AjaxWithData", // using hardcoded value for testing purpose type ...

After the data has finished loading, AngularJS will apply the directive to each select tag every time

I have created a directive that needs to be applied on each 'select' tag, but because it involves parsing the select data, it should be done after the data has been loaded. Unfortunately, the code I wrote only works on the last select item: ...

Exploring the functionality of Vue.js through Jasmine without the use of JavaScript modules

My task involves investigating unit testing for JavaScript on an older application that does not utilize JS modules (import/export). The app contains JS object/prototypes in external .js files that are imported via script src, and more recently, some Vue 2 ...

The mongoose.populate() method is failing to display the populated content

// defining user schema const mongoose = require('mongoose'); const {ChatRoom} = require('./chatRoom'); const userSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, username:{ type: 'String', unique ...

'An error occurred when invoking the class method due to 'This' being undefined

I'm attempting to display a response message to the user, but encountering an error (Cannot read property 'message' of undefined). Here's the code snippet causing the issue: server.js const server = express(); let App = require(' ...