Working with AngularJS 1.0.7: The art of nesting promises within $http

I am currently trying to grasp the concept of promises in Angular 1.0.7, but I find both the syntax and the idea challenging. Previously, I posted a related question Nesting promises with $resources in AngularJS 1.0.7 which is functioning correctly. However, when I attempt to achieve the same result using the $http service instead of $resource, it does not behave as expected.

The code does not wait for the promise to resolve, and I do not receive any output.

Below is the code snippet:

// Parsing URL to retrieve destination, language, and boatType       
var parseURL = function() {
    var language = $routeParams.language;
    var url = $location.path();

    var deferred = $q.defer();
    var promise = deferred.promise;
    promise.then(function success(result) {
        var destination = result;
        console.log("destination:" + destination);
        searchBoats(destination);
    });

    parseDestination(url, language).then(deferred.resolve);
};
parseURL();

var parseDestination = function(url, language) {
    console.log("parseDestination.begin");
    var departure = UrlService.parseUrlDeparture(url);

    var deferred = $q.defer(),
        promise = deferred.promise;
    TranslationService.getTranslatedDeparture(departure, language, API_SERVER_URL, deferred.resolve, deferred.reject);
    return promise;
};


// Service function
getTranslatedDeparture: function(destination, language, api) {
    var defered = $q.defer();
    var destinationPromise = defered.promise;
    $http.get("http://" + api + "/translatedDepartures?departure=" + destination + ";lang=" + language + ";matchStart=" + true).then(
        //var destination = result.data.map(function (source) { return source.element_translation; });
        defered.resolve
    );
    return destinationPromise;
}

Answer №1

Your approach to using promises is flawed in numerous ways. Promises are meant to be chained together by utilizing the .then() method, which not only resolves your bugs but also significantly reduces the length of your code. It's important to note that if you already have a promise to start with (such as the one returned by $http.get), there is no need for, and it is actually discouraged to use, $q.defer():

// One must parse the URL to extract destination, language, and boatType       
var parseURL = function() {
    var language = $routeParams.language;
    var url = $location.path();

    parseDestination(url, language)
        .then(function (result) {
            var destination = result;
            console.log("destination:", destination);
            searchBoats(destination);
        });    
};
parseURL();

var parseDestination = function(url, language) {
    console.log("parseDestination.begin");
    var departure = UrlService.parseUrlDeparture(url);

    return TranslationService.getTranslatedDeparture(departure, language, API_SERVER_URL);    
};


// Definition of the function within the service
getTranslatedDeparture: function(destination, language, api) {
    var url = "http://" + api + "/translatedDepartures?departure=" + destination + ";lang=" + language + ";matchStart=" + true;

    return $http.get(url)
        .then(function (result) { return result.data; });  
}

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

The method this.$refs.myProperty.refresh cannot be invoked as it is not a valid

I have added a reference value 'callingTable' to a vue-data-table (using vuetify) like so: <v-data-table :headers="callingTableHeaders" :items="getCallingDetails" class="elevation-1" ref="callingTable&quo ...

Executing a function only on one click

Recently diving into the world of JavaScript, I attempted to create a button that would log "hey" in the console upon being clicked. However, I encountered an issue where it logs "hey" before clicking the button and then does nothing when the button is act ...

Combining jQuery dataTables and Codeigniter for dynamic rendering using sAjaxSource

I am currently facing an issue while working with dataTables in Codeigniter. I keep encountering the following error message: array_push() expects parameter 1 to be array, null given The resulting output is {"aaData":null} My desired outcome should look ...

Angular Singleton Service for Asynchronous UI-Router Operations

I've been using UI-Router for my Angular application. The data I fetch through an asynchronous $http call helps in creating a connection object, which I want to make available as a singleton. My aim is to prevent potential timing issues that may arise ...

Guide to utilizing the app.locals parameter in JavaScript?

Currently I am in the process of developing a node.js application. In my app.js file, I have loaded a JSON file as app.locals.parameter and now I am attempting to utilize it in my index.hbs. Let's assume: app.locals.componentData = require('./m ...

Transferring Data from Angular Application to Spring Server via Rest Implementation

I am currently facing an issue while attempting to upload a file using Angular and send it to my Spring-based REST backend. I followed the guidance provided in this resource for my Angular service implementation. However, two problems have arisen: The fir ...

Emphasize links with larger background panels compared to the link object, minus any padding

http://jsbin.com/OkaC/1/edit HTML: <ul> <li> <a class='active' href='#'>Link</a></li> <li><a href='#'>Link</a></li> </ul> CSS: .active { bac ...

Making a POST request to an API by sending parameters through the URL

I have successfully created a web application using Ruby on Rails. Now, my next project involves developing a mobile app to complement the existing web platform. To accomplish this, I am utilizing Cordova and AngularJS (v1.2.13). The initial user interact ...

Position a dynamic <div> in the center of the screen

My goal is to design a gallery page with a list of thumbnails, where clicking on a thumbnail will open the related image in a popup div showing its full size. The issue I'm facing is how to center the popup div on the screen, especially when each pic ...

Include jQuery, jQuery UI, and plugins seamlessly to avoid any version conflicts

My goal is to inject my custom code into a webpage using a bookmarklet. This code requires jQuery, jQuery UI, and additional plugins to be included on the page. I'm aware of the noConflict function, but I have concerns about potential conflicts if ot ...

Two DataTables on a Single Page - Odd Initialization in the Second One

My page contains two dataTable elements and I've created a method as shown below: function ToDataTable() { $(".dataTable").css("width", "100%"); $(".dataTable").each(function () { var $that = $(this); /* Start of custom ...

Utilize AJAX, jQuery, and Symfony2 to showcase array information in a visually appealing table format

I have a requirement to showcase data utilizing ajax and jQuery in a table on my twig file. The ajax call is made with a post request to the controller, where the controller attempts to input several rows from a csv file into the database. However, there ...

How can I determine if a value exists in an array within an Angular template?

Is there a method to determine if a value is present in an array within an angular template? I would like something similar to this: <div ng-class="{'myClass': 1 in [1,2,5]}">Yay</div> If 1 is found in the array, myClass will be app ...

New to NodeJS: Utilizing Requestify to Retrieve Data from Another URL

As a newcomer in the world of NodeJs, I am faced with the task of transitioning my CodeIgniter server APIs to Node.js. Currently, I am utilizing requestify to retrieve data from a web service, and once this is accomplished, I intend to invoke an insert met ...

Leveraging JavaScript Functions in HTML

I am having an issue with a JavaScript file containing two similar functions that are executed through an HTML form. While the first function runs smoothly, the second function does not display correctly. It seems like I might be calling or executing the ...

``It seems like there was an error with WebComponents and NextJS - the hydration failed due to a mismatch between the initial UI and what was rendered on

I'm running into an issue with the following error message: Error: The initial UI doesn't match what was rendered on the server, leading to hydration failure. This problem occurs when I have a NextJS webpage that includes StencilJS web compone ...

What is the most effective way to implement Promises within a For loop?

const wiki = require('wikijs').default; const { writeFileSync } = require("fs") const dates = require("./getDates") //December_23 for (let i = 0; i < dates.length; i++){ wiki() .page(dates[i]) .then(page => p ...

Sort through a list of plans filtered by the month

I need help with organizing my plans by month. I am having trouble setting a header for each month and listing all the plans accordingly. Here is the data I have: const plans = [ { "done": true, "datetime": "2020-01-22T01:00:00+00:00 ...

Using the spread operator to pass properties in React

Update: After delving deep into the documentation, @wawka has discovered that there may be some issues with the react-router-dom v^5.0.1 causing problems with the myLink2 component. It seems like a rewrite of this component may be necessary. In my React p ...

What is preventing me from utilizing a dynamic import while working with Nuxt3?

I'm currently working on developing a component that allows me to dynamically import icons based on the provided icon name using unplugin-icons. However, I'm facing an issue where dynamic imports don't seem to work when the import path is dy ...