Fetching data using AngularJS and Ajax in a sequential manner

When working with the API, I need to load three different things:

  • users
  • groups
  • messages

Currently, my approach involves using $q.all() to load all three at once:

var loadAll = $q.all([
    getUsers.all(),
    getGroups.all(),
    getMessages.all()
]);

loadAll.then(function (data) {
    $scope.users = data[0];
    $scope.groups = data[1];
    $scope.messages = data[2];
};

Although this works, it doesn't load them in the specific order I want. I'd like to first load users, then groups, and finally messages.

I'm having trouble figuring out how to achieve this correctly...

The services return promises like so:

getUsers.all()
.then(function(data) {
    $scope.users = data;
};

But when I try chaining the promises together, they resolve as soon as users are loaded without waiting for others:

getUsers.all()
.then(function(data) {
    $scope.users = data;
    getGroups.all()
    .then(function(data) {
        // etc...
    }
};

How can I ensure that the API calls are made in the desired order?

Answer №1

One way to ensure that the datasets are loaded sequentially is by chaining promises:

getUsers.all().then(function(data) {
        $scope.users = data;
        return getGroups.all();
}).then(function(data) {
        $scope.groups = data;
        return getMessages.all();
}).then(function(data) {
        $scope.messages = data;
});

Using then in this manner guarantees sequential loading because each then call returns a promise.

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

Dividing JSON information into parts

I am attempting to present a highchart. I have utilized the following link: Highchart Demo Link Now, I am trying this web method: [WebMethod] public static string select() { SMSEntities d = new SMSEntities(); List<str ...

What is the best way to retrieve an object instead of an array?

When attempting to retrieve a JSON Object, I unexpectedly received an array instead. My query is based on the primary key, so I anticipate only one result. This is my current method : router.get("/student_info/:id", (req, res, next) => { connecti ...

jQuery smoothly sliding downward from the top to the bottom

http://jsfiddle.net/Hx65Q/3/ Is there a way to make the slider open from the top instead of the left side? $("button" ).click(function() { $('.login').toggle('slide', { duration: 1000, easing: 'easeOutBounce', }); ...

What exactly is the purpose of the script type importmap?

Can you explain the role of <script type="importmap"> and why it has become necessary for my code to function properly? <script type="importmap"> { "imports": { "three": "http ...

Out-of-office directive communicated through parsley.js

Perhaps this question may seem trivial, but I am struggling to find a solution to this dilemma. Currently, I am utilizing parsley.js for password field validation by using parsley's data-remote feature: Snippet Preview: <form data-parsley-valida ...

Issue with adding dynamic keys to state in Next.js using Zustand for state management not resolving

I've been experimenting with dynamically adding a key to a state in zustand. I've attempted various methods such as 1. const store = (set, get) => ({ keyAttrib: {key1: "value1", key2: 2}, update: (key, value) => { let new ...

What is the best way to highlight selected navigation links?

Recently, I implemented a fixed navigation bar with relevant links on a website. The navbar includes a jquery script for smooth scrolling when clicked. However, I am struggling to add a selected class to the clicked link. Despite trying various solutions f ...

Matching Arrays in Angular Made Easy

Hello friends! I'm seeking assistance since I'm a beginner in the world of Angular and TypeScript. export class TopPage implements OnInit { //city = localStorage.getItem('city'); city = 'bangalore'; areas_array = { ...

Using AngularJS, you can easily merge one array of data into another array

In my coding environment, I am working with two arrays. The first array is called `$scope.workingSchedules` and it contains data related to working hours for different days of the week. $scope.workingSchedules=[ { ...

Identifying the color category based on the color code in the props and displaying JSX output

I am in need of a solution to display colors in a table cell. The color codes are stored in mongodb along with their descriptions. I am looking for a library that can determine whether the color code provided is in RGB or hex format, and then render it acc ...

A new update is available for the UpdatePanel and ModalPopup Extender

I have structured my form as follows: <asp:Panel runat="server" Id="xyz"> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> 'Gridview featuring edit and delete options ...

Is there a way to calculate the upload ratio for a file upload progress bar without using a plugin or pre-made solution

Can someone provide guidance on how to create a file upload using iframe with an ajax effect? I am specifically looking for a way to track the uploading progress. While there are many plugins available, I would appreciate some ideas or examples to achiev ...

The JQuery functionality is failing to execute properly on Internet Explorer

I have developed a JQuery script that appears to be working perfectly in all browsers, except for IE 8. Interestingly, when I checked Internet Explorer's error details, it did not provide any specific information about the issue. Instead, IE simply po ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

Leverage the Angular 2 router for sending varying values to a single component

The issue lies in the fact that the code provided below for the component AppComponent remains constant across three different routes: /, /route2, and /route3. The problem arises as the properties title and bodyHTML of the AppComponent do not update with ...

Refreshing JSP Pages with Updated ActionBean Variables in Stripes Framework

Having recently started working with Stripes, I am trying to customize the number of records displayed on a paginated table based on the dropdown selection ("show ## records per page"). However, I am struggling to set the value of the "recordsPerPage" vari ...

How to showcase a list from intricate JSON data using Angular

I recently came across this pre-existing JSON data that I am unable to change: {"tags": [ { "title": "news", "options": [ { "title": "important", }, { "title": "less important", ...

Ng-Table doesn't bind properly when using NgTableParams with server-side data

Having trouble connecting the table with data obtained from a service. The controller code is shown below: app.controller('outletTypeController', ['$scope', '$location', '$timeout', 'outletTypesService', ...

Having difficulty adding a custom library from a repository into an Ember project as a dependency

I've been working on a WebGL library that I want to include as a dependency in an EmberJS project. It seems like I should be able to do this directly from the repository without creating an npm package, but I'm running into some issues. To illus ...

Utilize two functions to incorporate an array of strings into an object

Currently, I'm in the process of developing a NoteEditor using react. Within my popup, I have 2 text areas. However, I have encountered an issue when attempting to add my array of strings into an object. The variable containing the arrayOfStrings retu ...