error detection in the use of $q.all

I am currently utilizing a service that has the capability to fetch data for all dashboards within my system.

.service('dashboardServices', function ($http, $q) {
return {
    getData: getData
}

//defining promises and their respective http request URLs
var promise01 = $http({method: 'GET', url: urlpromise01, cache: false});
var promise02 = $http({method: 'GET', url: urlpromise02, cache: false});
var promise03 = $http({method: 'GET', url: urlpromise03, cache: false});

function getData(){
    var promises = [];
        var promises = $q.all([promise01, promise02, promise03])
                            .then(function(data){
                                setDashboardData(data[0].data);
                                setDashboardData(data[1].data);
                                setDynamicDashboardData(data[2].data);
                                })
        return promises;
}
})

Within my controller, I am using this service to trigger a modal window with a loading message while fetching data from the server.

.controller('MainCtrl', function($state, $scope, $ionicModal, dashboardServices) {
$ionicModal.fromTemplateUrl('views/loading.html', {
    scope: $scope,
    backdropClickToClose: false,
    hardwareBackButtonClose: true,
    animation: 'slide-in-up'
}).then(function(modal) {
    $scope.modal = modal;
});

$scope.openModal = function() {
    $scope.modal.show().then(function() {
        dashboardServices.getData().then(function() {
            $scope.closeModal();
        })
    })
}

$scope.closeModal = function() {
    $scope.modal.hide();
};
})

I am now seeking a way to display an appropriate message if the requests fail, as the loading modal window remains open in case of failures. I cannot use .error(function()... in my controller due to the restriction that .then().... .error() is not supported for $q.all. Is there a possible implementation for handling such exceptions?

Answer №1

.then(...).error(...) is not supported by $q.all or any other type of promises, including those from $q. This may be mistaken for the 'error' callbacks, and what you're actually seeking is catch:

$q.all([...]).then(onSuccess).catch(onError);

This can also be expressed as

$q.all([...]).then(onSuccess, onError);

However, it's generally considered more readable, as explained in this resource. In cases where it's necessary to handle errors from all(...) separately from the rest of the chain, it should be done like this:

$q.all([...]).then(onAllSuccess, onAllError).catch(onError);

Answer №2

fetchDataFromServer().then(function() {
    $scope.hidePopup();
}, function(error) {
    // manage the issue
});

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

Encountering an Unknown Error while Parsing JSON in Google Apps Script

Having trouble parsing JSON data retrieved from an API call. The error message "TypeError: Cannot read property "id" from undefined. (line 42, file "")" keeps popping up. I'm fairly new to Apps Script. Any thoughts on what might be causing this issue? ...

Pop-Up Buttons Generated in Real-Time

As a backend developer, I often find myself struggling to understand how web browsers work when working on frontend tasks. In this case, I have left the JavaScript alert for ease of use. Depending on which button is clicked in the popover, it should displa ...

Refreshing a React form

this.state = { name: "", arr: [], story: "" }; add(e) { e.preventDefault(); this.setState({ story: e.target.value }); this.state.arr.push(this.state.story); this.form.reset(); } <form action=""> <input onChange={this.b} type="t ...

Implementing Vue modal within a Laravel 5.2 foreach loop

I am facing a challenge with my Laravel blade template that uses a foreach loop to create a table with data. Each row has a link that triggers a modal when clicked. However, the issue is that clicking on any link activates the modal for every row instead o ...

Increasing the date field value in Mongoose, ExpressJS, and AngularJS with additional days

I encountered an issue while attempting to extend the number of days for an existing Date field in mongoose. Despite no errors being displayed in the browser or console, something seems to be amiss. Can anyone identify the problem in this code snippet? ...

Proper method for accessing the scope from a directive across several controllers

I have a directive called add-tags that I intend to use in various areas of the application. It is used to add tags to an array and then save them from the main controller. The user can edit the list when previewing on a different view or controller (modal ...

Error: An unexpected identifier was encountered while declaring a class attribute

class Data { title: string; fields: string[] = []; parent: string; attributes: any = {}; } Can someone help me out here? I'm encountering an issue. I am running node v14.17.0 This is the error message I'm seeing: title: string; SyntaxE ...

The propagation of onClick events in elements that overlap

Having two divs absolutely positioned overlapping, each containing an onClick handler. The issue is that only the top element's onClick handler fires when clicked. React 17 is being used. Here is some sample code: <div style={{ position: "abs ...

Is there a way to use JavaScript to modify the position of a div element

Can we adjust the div position using CSS (absolute or relative) with JavaScript? Here's an example code snippet: <div id="podpis" style="margin-top: 2rem;"> <div class="invoice-signature"> <span><?=$xml->sanitiz ...

Adding roles in ReactJS: A step-by-step guide

I am looking to enhance the admin's roles upon login to enable the creation of new users. Unfortunately, I am uncertain on how to add these roles and make them functional. Below is the code I have: Login.js class Login extends Component { cons ...

What is the method employed by Node.js to manage relative paths?

I am facing an issue with how Node.js handles paths. Despite checking the documentation, I couldn't find the solution to my problem. Basically, I have a file that contains a relative path pointing to another file (specifically a PNG image). Dependin ...

Designing motion graphics for a browser game

As I delve into learning about Node.js, Angular.js, Socket.io, and Express.js, my current project involves creating a multiplayer poker game like Texas Hold 'Em. However, despite spending a considerable amount of time browsing the internet, I have bee ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

reasons why the console is not logging updated states

I'm having trouble logging the updated state values after using setState. The values seem to be updating fine in the render function, but not in the tokenAccess() method. Can anyone explain why this is happening? import React, { Component } from &apo ...

route in mean stack isn't providing a response

I am having trouble creating a controller for /projects that should return all the data in the 'work' collection. The call is completing successfully with a status code of 200, but it is only returning an empty array or 'test:test' if u ...

AngularJS validation for minimum character count prevents character overflow

Encountering an unusual "issue". I've set up a form with a textarea that has both a minlength and maxlength validation. In addition, there's a straightforward character count displayed: <textarea ng-trim="false" ng-model="form.text" minlengt ...

Ways to send a query parameter to parse-rest-api using the $http service in AngularJS

Currently in the process of learning AngularJS, I have set up my development environment with Sublime Text as my editor and Parse.com REST API as the backend layer. I encountered a situation where I needed to retrieve data based on a specific attribute. ...

A guide to retrieving a Discord user's name and discriminator with Discord.JS

I have encountered an issue while programming a discord bot recently. One of the challenges I am facing is that I have created an object array to store a user and a string when they execute l!start. However, I am unsure of how to retrieve a user's na ...

"Transitioning from jQuery to Vanilla Javascript: Mastering Scroll Animations

I'm seeking guidance on how to convert this jQuery code into pure Javascript. $('.revealedBox').each(function() { if ($(window).scrollTop() + $(window).height() > $(this).offset().top + $(this).outerHeight()) { $(this).addCla ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...