Is the fulfillment of AngularJS $q promises determined by the return value?

I'm currently working with angularjs 1.6.1 and $q. My task involves fetching a large amount of data from an API. I'm struggling to grasp when promises are actually fulfilled. Here's a snippet of what I'm doing:

// controller
this.dataOnePromise = dataOneService.get().then(function (response){
    $scope.dataOne = response.data;
    return $scope.dataOne;
});

this.dataTwoPromise = dataTwoService.get().then(function (response){
    $scope.dataTwo = response.data;
    return $scope.dataTwo;
});

let promises = [this.dataOnePromise, this.dataTwoPromise];

$q.all(promises).then(function(response){
    // data has been loaded!
    // I can now access $scope.dataOne and $scope.dataTwo
});

All the service methods follow a similar structure:

 // service. Only the method is shown here
 get: function() {
    var defered = $q.defer();

    $http.get('my api endpoint').then(function(response) {
        defered.resolve(response);
    }, function(err) {
        defered.reject(err)
    });

    return defered.promise;
}

I'm uncertain if I'm introducing a race condition by not explicitly returning values in the `then` handlers of dataOneService and dataTwoService, potentially causing $q.all(promises) to be fulfilled before the data is assigned to the scope. Can anyone clarify when $q.all(promises) is actually fulfilled? Does it depend on the returns?

Thank you for your assistance.

Answer №1

Referencing the documentation https://docs.angularjs.org/api/ng/service/$q

all(promises);

Bringing together multiple promises to form a unified promise that resolves once all individual promises are resolved.

It yields a singular promise that will resolve with an array/hash of values, each corresponding to the promise at the same position in the original array/hash. If any promise is rejected, the resulting promise will also be rejected with the same value.

Regarding your concerns, Could there be a race condition? No, as both calls are asynchronous and $q.all() ensures it waits for all promises to resolve.

When exactly does $q.all(promises) get fulfilled? Does it depend on the return values? Yes, once again, $q.all() is fulfilled only when every promise is resolved.

========== extra=====

Personally, I suggest using a hash for promises to provide clear names for future reference.

var promises = {};
promises.promiseA = ...;
promises.promiseB = ...;

$q.all(promises).then(function(result){
   console.log(result.promiseA);
   console.log(result.promiseB);

});

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

Verify the functionality of JavaScript to ensure it is enabled and functioning properly

I have experimented with various methods to determine if JavaScript is enabled and running correctly. Typically, I would use a simple test like this: $('.jstest').html('JavaScript works.'); <p class='jstest'></p> ...

AngularJS - Increase the input date by 6 hours before converting it to JSON

Is there a way to add 6 hours to an input date in AngularJS? I attempted the following code: var eventStart = new Date ($scope.event.startdateid); var startDate = new Date ( eventStart ); startDate.setHours ( eventStart.getHours() + 6 ); event.startdate ...

Can someone explain the significance of this in an HTML form?

Can anyone explain the following code snippet found in a web form? I found this button code on a webpage, but I'm having trouble understanding it. Could someone provide some clarity? <input type="submit" name="ctl00$ContentPlaceHolder1$Button8" v ...

Exporting all components using require: A complete guide

Currently, I am working on a Vue js application where I am tasked with exporting all the files and components from a specific directory. These files/components need to be imported into a separate file named paths.js. If I use the require function to impor ...

Angular schema forms allow users to make multiple selections at once through a

Having an issue with using a multiselect checkbox in a dropdown with Angular Schema Forms. My requirement is to disable another control based on a selected value, but I am unable to bind any events to the checking of a checkbox in the multiselect. Can so ...

Having trouble embedding Hangouts button in HTML template using script tags

When I include a Hangouts button on my index page, it is visible and functional as expected: <body ng-app="sampleApp" ng-controller="MainCtrl"> <div class="row"> <div class="col-md-12 m-body"> <div class="m ...

Steps for creating a functional counter in AngularJS

I am attempting to create a counter in AngularJS that will be used for some other purpose once it is working with a variable. However, I am facing an issue where the variable is not updating as expected. Since this will eventually become a more complex com ...

Content OverFlow: DropDown Menu is not overlapping the content, but rather pushing it downwards

In my webpage, I have a drop-down menu that traditionally pushes the content below it down to make space for its items. However, I want the drop-down to overlap the contents below without affecting their position. I've tried various solutions, such a ...

The anchor tag fails to trigger the onClick function in React

I'm having trouble updating the component state in my React app when clicking on an anchor tag within the render method. I've attempted to bind the function in the constructor, but the console.log statement is still not being called. Here's ...

Hash functionality does not cooperate with the back button, requiring the use of JavaScript to trigger a function when the URL changes

Hi everyone, I have a code snippet that is designed to read the value after the hash in the URL and display a specific div based on that value. It works as expected, except for when the hash is changed while already on the site or when navigating back with ...

Ways to add a line break within JavaScript code

I am currently developing a bot for my Discord server and working on logging messages to a text file. All the necessary information about the message is stored in a variable named logger, and I am using Node.js to append my log file. When attempting to ad ...

Using Ruby instead of Javascript in lessc

My CSS is compiled in a node application using lessc. LESS was installed via NPM. When I check the current version of lessc --version it shows lessc 1.3.3 (LESS Compiler) [Ruby] 2.3.2 How can I change it to display lessc 1.3.0 (LESS Compiler) ...

JQuery .click Event doesn't center elements even with transform-origin adjustment

In the JSfiddle provided below, you can see that after a click event occurs, two span (block) elements rotate 45deg to form an "X". However, both elements are slightly shifted left, creating an off-center "X" relative to the parent's true center-origi ...

How to dynamically populate a Vue multiple select dropdown with v-for loop?

I have been attempting to implement multi-select questions in Vue using v-for. The Select menu and its options are populated via JSON data. Unfortunately, I am facing difficulty in retrieving the selected results as expected. Whenever I select an option ...

Tips for customizing the appearance of a Link component while it is the active page in Next.js

I'm seeking advice on how to style an anchor component differently when it is active on a page. Here's the code I have so far: import Link from 'next/link'; import styled from 'styled-components'; const NavStyle = styled.nav` ...

"Encountering a connectivity problem with Apollo server's GraphQL

I am facing a networking issue or possibly a bug in GraphQL(Apollo-Server-Express). I have tried various solutions but to no avail. When sending a query, everything seems perfect - values checked and request showing correct content with a 200 status code. ...

Maintaining Scope Across GET Requests in Angular

Below is the code snippet that I am working with: $http({ method: 'GET', url: 'http://localhost:8080/getStuff' }).then(function successCallback(response) { $scope.stuffData= response.data.length; }, function error ...

How can I put a row at full-width in a Material-UI table in React

I need assistance with displaying data in a table using JSX code: const StudentsTable = (props) => { const classes = useStyles(); return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple ...

Whenever I attempt to include additional drop-down lists, jQuery fails to function

My webpage features multiple drop down lists, with one populating based on the selection from another. Additionally, I have included a button at the bottom of the page. When this button is clicked, I need to add another column to the page. However, after ...

Safari-exclusive: Google Maps API dynamically altering page aesthetics post-loading

Recently, I encountered a peculiar problem. Upon loading a page, the text displayed with full opacity. However, upon the Google Maps API loading after 2 seconds, the entire page's styling suddenly changed. It was as if the text on the page became less ...