incapable of utilizing the $q library and promises

I am trying to make use of the variable StatusASof within the inserthtml function in the following manner.

App.controller("SS_Ctrl", function ($scope, $http, $location, $window, $sce, $q) {

var ShiftDetails = []; 

   function acquireMAStatusASof(Id) {
        var defer = $q.defer();
        $http({
            method: 'GET',
            url: 'http://xx/api/Sxxx/GetMAStatusASof',
            params: { Id: Id }        
        }).then(function successCallback(response) {            
            StatusASof = response.data;           
            alert("acquireMAStatusASof : " + StatusASof);  
            defer.resolve(response);
        }, function errorCallback(response) {});
    }

 function insertHtml(dates, ShiftDetails, Id) {

       // var promise = acquireMAStatusASof(Id); promise.then(

        var defer = $q.defer();
        acquireMAStatusASof(Id); 
    alert(StatusASof);  
    defer.resolve();       
        var Content;
        Content = '<table class="clsTable">  <tr>  <td rowspan="2">Cases ' + $scope.StatusASof + ' </td>  <td rowspan="2">Total</td> ';
        for (var i = 0; i <= 6; i++) {
            if (i == daySeq - 1) {            
                Content = Content + '<td colspan="3"  style="background-color:red"> {{dates[ ' + i + ']}} </td> ';
            }           
        }
}

However, $scope.StatusASof remains undefined when attempting to display the outcome. It appears that $q.defer is not functioning as expected.

What steps can I take to ensure that the code continues execution only after receiving data from getMAStatusASof(Id);

If anyone could provide assistance with this issue, it would be greatly appreciated.

Answer №1

Latest Update:

To retrieve the result, make sure to include return defer.promise; in your code.

function checkStatus(Id) {
    var defer = $q.defer();
    $http({
        method: 'GET',
        url: 'http://xx/api/Sxxx/GetMAStatusASof',
        params: { Id: Id }        
    }).then(function successCallback(response)  {            
        StatusAsOf = response.data;           
        alert("checkStatus : " + StatusAsOf);  --> Data received from API shown here.
        defer.resolve(StatusAsOf);
    }, function errorCallback(response) {
         deferred.reject(false); 
    });
    return defer.promise; 
}

You can then call this function like so:

checkStatus(Id).then(function(result){
  if(result){
    $scope.StatusAsOf = result;
  }
})

Answer №2

Avoid using $q.defer() in this scenario...

Simply implement

function getMAStatusASof(Id) {
  return $http({
    method: 'GET',
    url: 'http://xx/api/Sxxx/GetMAStatusASof',
    params: { Id: Id }        
  })
  .then(function successCallback(response) {     
    return response.data;
  })
  .catch(function errorCallback(response) {
    return null;  //Ignore the error and return null instead.
  });
}

Then, utilize

getMAStatusASof(Id).then(function(result) {
  console.log(result);
});
//No need for .catch as all potential errors are handled within the getMAStatusASof function

If you insist on using $q.defer(), then the function should return defer.promise, similar to what Jazib mentioned.

However, utilizing $http already provides a promise, rendering the use of $q.defer() + return defer.promise unnecessary.

Save that approach for situations where you require wrapping something not inherently returning a promise. For instance, when monitoring the closure of a bootbox modal

function notifyMeOfClosing() {
  var deferred = $q.defer();
  bootbox.confirm("This is the default confirm!", function(result){ 
    if(result) {
      deferred.resolve();
    }
    else {
      deferred.reject();
    }
  });
  return deferred.promise;
}

Answer №3

Encountered an issue updating @Daniël Teunkens' post with the provided code snippet (from "}" to ")"). Therefore, presenting a new answer instead.

getMAStatusASof(Id).then(function(result) {
   // Insert your code here along with your HTML content.
     ....
  console.log(result);
})

This solution should hopefully resolve the problem.

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 best 'event' to pair with an <input/> element in iOS/Android development?

Looking for a way to toggle results when a user starts typing in a search field? Here are some event options: mousedown / mouseup touchstart / touchend focus You could also consider using the "change" event instead of "click" to check for text input an ...

Creating a custom request for the Upload component in Ant Design Vue requires a specific set of steps and

I attempted to implement the solution provided in How should customRequest be set in the Ant Design Upload component to work with an XMLHttpRequest? but it doesn't seem to be working for me in Ant Design Vue. Could someone provide an example, please? ...

Navigating to a form within an Angular-UI uib-tab

Is it possible to access a form within a uib-tab for validation purposes? To see an example, check out this plunker: http://plnkr.co/edit/8hTccl5HAMJwUcHEtnLq?p=preview While trying to access $scope.forminside, I found that it's undefined (referring ...

"Transforming JSON data into a format compatible with Highcharts in PHP: A step-by-step

Currently facing an issue with converting the given array format into a Highcharts compatible JSON to create a line chart. Although everything else is functioning correctly, I am struggling with this specific conversion task. { name: [ 1000, ...

Tips for setting React state using variables as keys or values

Although I managed to achieve the desired result, I'm still puzzled as to why my more straightforward approaches didn't work. Can someone help me understand what's going on here? Basically, I needed to set nested state at different levels u ...

Leverage the power of Shopify API to retrieve a list of all products by making a request through

My website is custom built on node.js, and I am looking to retrieve all of my products in a single GET request. Unfortunately, the Shopify buy-button feature does not allow me to display all products at once due to pagination, hindering my ability to effec ...

Displaying information in form using ajax within the laravel framework

I am currently utilizing ajax to retrieve data from a database. While I am able to successfully retrieve the data on the backend, I am facing difficulties displaying it in the input field below. I have tried writing some code, but it seems that the JavaScr ...

How can items be categorized by their color, size, and design?

[{ boxNoFrom: 1, boxs: [{…}], color: "ESPRESSO", size: "2X", style: "ZIP UP" { boxNoFrom: 13, boxs: [{…}], color: "ESPRESSO", size: "2X", style: "ZIP UP" }, { boxNoFrom: ...

Is it possible to retrieve real-time scores of the players from espncricinfo through Node.js with the help of Cheerio parser?

Currently, I am facing an issue with retrieving live scores of individual players from espncricinfo. Despite my efforts, I have not been successful in fetching this data. Although some data is being retrieved dynamically, the scores are not showing up. Th ...

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

Is there a way to use SCTP with Socket.io and Node.js?

I have a new project in the works, creating a web application that will utilize web sockets to provide real-time updates for users. The plan is to seamlessly transmit changes from the back-end engine. My challenge lies in Node.js not supporting SCTP sock ...

Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggest ...

Minimize a collection of JavaScript objects

I am working with an Array of objects where I need to return the collection as an Object, with the key names being the indexes of their length. Additionally, I have to filter this object based on its values. Check out my code snippet below: const data = ...

Encountering difficulties during the migration process from a JavaScript to a TypeScript React Component

I've encountered some challenges with configuring TypeScript in my project. Initially, I developed my application using plain JavaScript. However, eager to learn TypeScript, I decided to convert my JavaScript project into a TypeScript one. To achiev ...

Executing a function within a VueJs 2 component immediately after it has finished loading

How can I retrieve data after a component has finished loading? When I initialize my Vue instance and load the component, the template loads correctly but the functions in the mounted lifecycle hook are not executed, causing the stats object to remain empt ...

Error encountered: Element cannot be clicked on at specified coordinates - Angular/Protractor

Recently, I have been testing out CRUD functionality in an Angular app using Protractor. One recurring issue I've encountered is with the create/edit buttons, which all open the same modal regardless of the page you're on. The frustrating part i ...

Text below a stationary header

I need some help with my code using material-ui-next beta.30. The issue I am facing is that the content within mui.Paper is appearing behind the AppBar instead of below it. Here's my current setup: import * as React from 'react'; import * a ...

Preventing nested prototype methods from being transferred between objects in a WebWorker

My challenge is to reserialize an object from a WebWorker while maintaining the same definitions. However, upon receiving the message, all of the prototype functions are lost. The current solution I have only works for first level prototype functions, bu ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

What makes this lambda function in TypeScript successfully execute without any errors?

I was under the impression that this code let x: (a: { b: number }) => void = (a: { b: number, c: string }) => { alert(a.c) }; x({ b: 123 }); would result in an error because the lambda function requires an additional property on the a argument, m ...