AngularJS utilities $http and $q

I recently started learning about Angular JS $http and $q services through a tutorial on Pluralsight. I focused on creating the eventData service to fetch JSON data from the server using promises, but encountered an issue when trying to assign the promise to $scope.event - it showed up as an empty object. I wondered why my original method didn't work.

After searching online for a solution, I came across a different code snippet that utilized the "then()" function on the promise to properly assign the result to $scope.event.

It struck me that the promise queue is typically meant to eliminate the need for passing callbacks, yet in this case, we are essentially passing a callback to the "then" function. This made me question if it defeats the purpose of having a promise queue in the first place.

// Event Data Function
eventsApp.factory("eventData", function($http, $q){
    return {
        events : function() {
            var deferred = $q.defer();
            $http({
                method: "GET", url:"http://localhost/data/events/events.php"
            })
                .success(function(data,status,headers,config){
                    deferred.resolve(data);
                })
                .error(function(data,status,headers,config){
                    deferred.reject(status);
                });
            return deferred.promise;
        }
    }
});

// Original Event Controller
var eventController = eventsApp.controller('eventController',function($scope,eventData)    
{
    $scope.event = eventData.events()
});



// Revised Event Controller after research
var eventController = eventsApp.controller('eventController',function($scope,eventData)    
{
    eventData.events().then(function(result){
        $scope.event = result
    });
});

Answer №1

The purpose of using promises is to avoid the mess of nested callbacks, also known as callback-hell. They ensure that your asynchronous functions return before executing the next one, especially when the next function relies on data from the previous one.

Once the promise is fulfilled, the function provided in .then() is triggered and given access to the previously retrieved data as arguments.

It's important to note that there's no need to wrap $http in a promise since it already returns a promise inherently.

Answer №2

Escaping the callback hell with the promise queue can make your code much easier to follow and debug.

In a traditional callback hell scenario...

var callback3 = function(param) {
  console.log(param);
}

var callback2 = function(param, callback) {
  setTimeout(function() {
     param = param + "end";
     callback(param);
   }, 100);
}

var callback1 = function(param, callback) {
  setTimeout(function() {
     param = param + "the ";
     callback(param, callback3)
   }, 100);
}

var someFunction = function(param) {
   setTimeout(function() {
     param = param + "am ";
     callback1(param, callback2);
   }, 100)
}

someFunction("I ");

But by implementing promises, we can simplify our code structure.

   var somePromise = $q.defer();

   var callback3 = function(param) {
      console.log(param + "end");
    }

    var callback2 = function(param) {
      setTimeout(function() {
         return param + "the ";
       }, 100);
    }

    var callback1 = function(param) {
      setTimeout(function() {
        return param + "am ";
      }, 100);
    }

    var someFunction = function(letter) {
      //could for example be after an http req or some async call.  
      setTimeout(function() {
        somePromise.resolve(letter);
      }, 100);
    }

    someFunction("I ");

    somePromise.promise
      .then(callback1)
      .then(callback2)
      .then(callback3);

Debugging is certainly more pleasant with promises in place.

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

Cannot retrieve style information using getComputedStyle on iOS devices

Hi there! I've created a function that is supposed to return a specific computed style from a given element. It seems to be working perfectly fine in all desktop browsers that I've tested, but unfortunately, it's not functioning properly in ...

Transform date format using VueJS in JavaScript

I need to convert a date format from 19 Oct 2017 to 20171019. Is there a way to do this quickly? I am using FlatPickr in VueJs. Here is the code snippet for reference: import flatPickr from 'vue-flatpickr-component'; import 'flatpickr/dist/ ...

Creating a Variable in AngularJS with ngInit

Essentially, I am passing a variable from PHP to Angular JS. I am echoing the PHP variables inside the ng-init tag and it displays correctly (ng-init="listing=5;user=59"). <div id="content" ng-app="galleryApp" ng-controller="galleryController" ng ...

I encountered an error from DataTables when trying to set the width of the header cells using the original width of the columns

                 Help! I keep getting an error message: DataTable Uncaught TypeError: Cannot read property 'style' of undefined Does anyone have any ideas on how to fix this?   I keep seeing the following error message: Uncaught Typ ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

Omit a Mongoose field in a query by utilizing the assignment operator

Despite recognizing that this question has been posed previously, I have not been able to find a solution suitable for my specific scenario. Many websites recommend using .select('-queryData'), but I am unsure how to implement it in my case. My ...

Exploring the World of Subclassing Arrays in JavaScript: Uncovering the TypeError of Array.prototype.toString's

Can JavaScript Arrays be subclassed and inherited from? I am interested in creating my own custom Array object that not only has all the features of a regular Array but also contains additional properties. My intention is to use myobj instanceof CustomArr ...

Send the text information from the drop-down menu

Does anyone know how I can transfer the selected text from each select box to its corresponding (textbox)? The select boxes contain integer IDs, and I want to save the text of each selected option to a database. I'm having trouble with my script for ...

AngularJS - Viewless and Issue-Free

I'm currently working on a project that involves using AngularJS and PHP. I made some changes, but now it's not functioning properly... The issue is that there are no errors in the console, Angular works (I can retrieve its version), but my vi ...

Eliminating the use of undefined values in select dropdown options

My current code reads an uploaded text file and sorts it into options for different <select> elements. However, I'm encountering an issue where once the entire text file is read, additional options appear as undefined. Does anyone know how to pr ...

jQuery .html() function malfunctioning

I am just starting out with front-end development and have taken on the challenge of creating a simple Tic Tac Toe game using HTML5. To set up the game board, I decided to use a table element in my code. Below is the snippet of HTML that I have implemented ...

Tips for utilizing a variable from a function in one file within a function in another file

Having trouble using the variable counter from one function in a different file? In the first function, I defined counter without using "var" thinking it would make it a global variable. But for some reason, it doesn't seem to work. Help needed! //fun ...

Unusual Methods in Vue.js: Exploring Odd Behavior

In my application, I have a single data variable called message, as well as a method in the methods section that performs cryptographic algorithms. Below is the code snippet: export default { data: () => ({ message: "" }), methods: { clic ...

"The FindByIdAndUpdate function is successfully updating the data, but it is unexpectedly

This is my first time seeking guidance here, as I've reached a dead end with my issue. I am currently working on a household collection that includes a member collection within it. Whenever new members join, I need to update the household collection ...

"Encountered a Parsing Error: function keyword was an unexpected token in an Async Function using a more recent version of Node

In the process of working on a side project, I am utilizing node and firebase technologies. While I have successfully created regular functions and cloud functions, I encountered an issue when attempting to create an async function like so: async function ...

Adapting CSS properties dynamically in PHP/JS according to the selected language

I have been implementing a method to incorporate multiple languages into my website, following the guidelines provided in this resource: However, I'm currently encountering an issue where the button name is specified in CSS using "content: '&apo ...

JavaScript height problem

I have a JavaScript code that is supposed to add either the class "vertical" or "horizontal" to all image articles on a page. The issue I am facing is that the code always adds the class "horizontal" even to photos that should have the class "vertical" (sp ...

beforeunload event confirmation prompt

I am currently working with Laravel and Vue.js to create a multi-step wizard. Within this wizard, I have implemented the onbeforeunload event to prevent any unwanted actions by displaying a confirmation message. However, I am encountering an issue where th ...

I am encountering a 302 error when attempting to sideload images on Imgur using the API

I've been experimenting with sideloading using imgur's API. $.get("http://api.imgur.com/2/upload.json?", { url: www.example.com/blah.jpg },function(response){ var url = response.upload.links.original; var thumb_url = response ...

Is it possible to automatically reload the previous link when the back button of the browser is clicked?

I am working on a website where the main content is loaded using jQuery Ajax based on the selected menu item. When a menu item is selected, the URL changes according to this pattern: http://host/domain/index.php?pageid=page In this scenario, the 'p ...