Angular's $q.defer() function will yield an object with a "then" function

In my Angular file, I am attempting to access a database using $http and then store the retrieved data in a $scope variable for display on the webpage. However, I am encountering difficulties with $q.defer not running as expected. When I check the console.log() inside the $http function, it displays an object containing the database response data. But when I call the function, it only logs Object {then: function}. The actual data is within this object but seems to be accessed through Object.$$v, which I am unsure about.

var app = angular.module("app", []);

app.factory('portfolioFactory', function ($http, $q) {
        var obj = {};
    obj.getResponse = function(){
        var deferred = $q.defer();
        $http.get('./../includes/portfolio/db_access.php').success(function(data){
                deferred.resolve(data);
                console.log(data);
        });
        return deferred.promise;
    }
    return obj;
});

app.controller("PortfolioCtrl", function($scope, portfolioFactory) {
    $scope.PortfolioItems = portfolioFactory.getResponse();
    console.log($scope.PortfolioItems);
});

Answer №1

$http.get( ... );

Delivers a commitment.

app.controller("PortfolioCtrl", function($scope, portfolioFactory) {
    portfolioFactory.getResponse().then(function(response) {
        $scope.PortfolioItems = response.data;
    })
});

Works as expected.

In previous Angular versions, using

$scope.PortfolioItems = portfolioFactory.getResponse();
would have sufficed, but in newer versions, the automatic unwrapping of promises no longer occurs.

A promise serves as a more elegant way to manage asynchronous actions (a design pattern). Instead of conventional callback usage, one can line up callbacks with promise.then( callback ). Subsequently, when deferred.resolve is executed, the callbacks receive the outcomes. If the promise has already resolved before the callbacks were added, they are immediately triggered with the cached information. This approach is far superior to writing code with multiple nested query( callback ) calls that often lead to callback hell.

Alternatively, the following could be done since every result of an $http request is already a promise:

app.factory('portfolioFactory', function ($http) {
    var obj = {};

    obj.getResponse = function(){
        return $http.get('./../includes/portfolio/db_access.php').then(function(data){
           console.log(data);
           return data; //Pass on the data further up.
        });
    }
    return obj;
});

Answer №2

To access your data, simply use the "then" function.

app.controller("PortfolioCtrl", function($scope, portfolioFactory) {
    $scope.PortfolioItems = portfolioFactory.getData();

    $scope.PortfolioItems.then(function(results){
        console.log(results);
    };
});

For clarity, consider labeling variables like this....

app.controller("PortfolioCtrl", function($scope, portfolioFactory) {
    $scope.PortfolioItems = null;
    var fetchPortfolioItems = portfolioFactory.getData();

    fetchPortfolioItems.then(function(results){
        $scope.PortfolioItems = results;
        console.log($scope.PortfolioItems);
    };
});

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

Why can't the data I store in rootScope be accessed within a directive?

I have defined the following: function appRun( $rootScope ) { $rootScope.abc = 99; } I am using a directive in this manner: <admin-retrieve-button ctrl="exam" home="home" Network="Network"></admin-retrieve-button> This is my dir ...

When I try to use Node.js and Express, I encounter an issue where I receive the

I recently developed a basic application. Everything was running smoothly until I decided to organize the code using an MVC template. However, now when you visit localhost:3000/add-service, you are greeted with a "Cannot Get /add-service" error message. W ...

Utilizing AngularJS to upload numerous independent attachments to CouchDB

My goal is to upload multiple files to a couchdb document using angularjs. Despite my efforts with an angular.forEach loop, I am facing issues as the asynchronous $http calls do not wait for the previous loop to finish before moving on to the next one. Her ...

What is the best way to restrict the input year on @mui/x-date-pickers to a certain range?

Is there a way to restrict the input year range when using @mui/x-date-pickers? I want to limit it from 1000 to 2023 instead of being able to enter years like 0000 or 9999. https://i.stack.imgur.com/0p6j3.jpg I have tried adding a mask to InputProps in my ...

issue in jquery: ajax promise not returning any value

My code snippet: var testApp = (function($){ var info = [{ "layout": "getSample", "view": "conversations", "format": "json", }]; var Data = 'default'; function fetchInfo(opt) { return new Promis ...

Using ui-sref to transmit data attributes

Is there a way to pass extra data into the controller from within ui-sref? Currently, I am iterating through a JSON object and including data in the sref: <a data-imgName="{{ img.name }}" data-imgDesc="{{ img.desc }}" ui-sref="main.imgDesc({imgid: &apos ...

I want to establish a connection between my AngularJS front-end and two separate socket connections that are active on two different Express servers. How can I achieve this

Currently, I have a web application that utilizes a socket connection between my front-end AngularJS and Express server. However, I now need to incorporate another socket connection to listen for events from an additional server. Is it possible to achiev ...

Enhance vue.js by adding your own custom filters

I am currently working with Vue.js integrated with Laravel using Elixir and Browserify. I am trying to create custom global filters, each in their own separate file. Despite following the documentation, I am encountering an issue where I receive the follow ...

What is the best way to utilize MongoDB with promises in Node.js?

I've been exploring how to integrate MongoDB with Node.js and the documentation suggests using callbacks. However, I personally prefer working with promises. The issue is, I haven't figured out how to implement promises with MongoDB yet. I attem ...

The vertical scrolling feature seems to be disabled for ng-repeat within the Angular view

I have a list of customers coming from the backend that I need to populate into ng-repeat. However, even though there are more customers, the vertical scroll is not visible. Why is that? <link rel="stylesheet" href="hike.css"> <div ng-show=' ...

When a row is clicked, retrieve the data specific to that row

I have implemented a data-grid using react-table where I pass necessary props to a separate component for rendering the grid. My issue is that when I click on a particular row, I am unable to retrieve the information related to that row using getTrProps. ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...

EBUSY: Unable to access resource due to being busy or locked, unable to retrieve information from 'C:hiberfil.sys'

I am running into an issue while attempting to publish an npm package. The error message I keep receiving is causing me some trouble. Does anyone have any suggestions on how I can resolve this? Your help would be greatly appreciated! Thank you in advance ...

Creating and displaying images dynamically on a webpage using JavaScript after it has finished loading

I am trying to load images from an array and display them on a webpage upon the browser window loading. Here is my approach: const players = [ { photo: 'img/photo0.jpeg' }, { photo: 'img/photo1.jpeg' }, { ...

Are elements in React Native PanResponder capable of being clicked?

While I have movable panresponders, I also require the ability to click on one for an onPress event. Is it achievable? At present, they are <View> elements. If I attempt to switch them to <TouchableOpacity> or a similar element, it results in ...

Inline display malfunctioning

I am facing an issue while integrating ngTimepicker into my Angular project. It is functioning properly, but I am unable to inline the ngTimepicker inputs with the form input. Check out the plunker here I would like this section of HTML to be displayed in ...

From jQuery to Vanilla JavaScript: Implementing a simple click event listener

I've been attempting to translate the following jQuery code into vanilla JavaScript, however, I can't get it to function properly. jQuery: $(document).ready(function() { $("button").click(function() { var char = "0123456789abcdefghijklmno ...

"Maximizing Efficiency: Chaining Several Actions Using the JavaScript Ternary Operator

When the condition is true, how can I chain two operations together? a = 96 c = 0 a > 50 ? c += 1 && console.log('passed') : console.log('try more') I attempted chaining with && and it successfully worked in react, b ...

Employing conditional statements to adjust the size of an image or background identifier in JavaScript

As I dive into the world of Javascript, I find myself faced with the challenge of modifying existing code using if / else statements. The original code snippet in question is as follows: document.getElementById("button1").addEventListener("click", functio ...

Sending Python array data to an external Express.js server

Managing data in the backend, is a python program(vmstats.py) that stores string information in vmonoff[]: vmstats.py import json from proxys import ProxyServer vmonoff = [] proxys = ProxyServer('XXXXXX','UUUUUU','PPPPPP') ...