Anticipating the resolution of one promise before tackling the next in Angular.js

Is it possible in Angular.js to ensure that a given promise is resolved before another dependent promise?

Consider the following code snippet:

User.getAllUsers().then(function(users) {
    $scope.users = users;
    for (var i = 0; i < users.length; i++) {
        console.log('username ' + users[i].username);
        Message.getUnreadMessages(users[i].username, localStorage.getItem("token")).then(function(messages) {
            console.log('username in second promise' + users[i].username);
            $scope.messages.push(messages);
        })
    }
})

The services User and Message are being utilized here.

The first

console.log('username '+ users[i].username);
correctly displays the username of each user.

However, the second

console.log('username in second promise'+ users[i].username);
results in the error message:

Cannot read property 'username' of undefined

Answer №1

Check out this solution:

User.getAllUsers().then(function(users) {
    $scope.users = users;
    for (var i = 0; i < users.length; i++) {
      (function(user){
        console.log('username ' + user.username);
        Message.getUnreadMessages(user.username, localStorage.getItem("token")).then(function(messages) {
            console.log('username in second promise' + user.username);
            $scope.messages.push(messages);
        })
      })(users[i]);
    }
})

For more information on closures and loops, visit https://developer.mozilla.org/en/docs/Web/JavaScript/Closures.

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

Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function. Below is a sample code snippet demonstrating this: var xhr = new XMLHttpRequest(); function getData(e) { if (xhr.readyState === 4) { if (xhr.s ...

Issue: Reactjs - Material-UI HTML Tooltip does not display dynamic HTML content.In the Reactjs

I have been using a customized HTML MUI Tooltip. Currently, it is functioning with static content but I am looking to make it dynamic. Unfortunately, it is not working with dynamic HTML content. Here is my attempted approach: const ADJUSTMENT_HELP_TEXT = ...

Effortless method to handle package.json configurations

Is there a better approach for seamlessly transitioning between using npm link and git, or another solution that caters well to both front end and back end developers? The dilemma I'm facing revolves around developing a website that utilizes multiple ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...

What is the process of using a For loop to output a string in reverse order?

I'm attempting to reverse the string "hello" using a For loop, aiming for the output of "olleh". However, I'm facing an issue where the last character in the string is not being removed after being added to the array. Consequently, only the last ...

Is there a way to customize the color of the like button?

I'm trying to create a Twitter-like button with an icon that changes color. When the button is clicked, it successfully changes from gray to red. But now I'm stuck on how to make it switch back from red to gray. I am currently using javascript ...

Using Vue components alongside vanilla JavaScript code

I am currently working on integrating Vue.js into an existing project that does not utilize Vue. Unfortunately, I have been unable to find any resources or documentation on how to create a Vue component with an API that can be accessed by external code out ...

The value of type 'X' cannot be assigned to type 'Y' or 'undefined'

In my code, there is a component that requires a prop with an enum value: export enum AType { some = "SOME", word = "WORD", } const MyComponent = (arg: AType) => {} When I try calling this component like so: <MyComponent ar ...

Interacting with a 3D model using the mouse cursor in a three

After stumbling upon the three.js library recently, I've been spending several days experimenting with it. I am eager to incorporate a mouse event into my project similar to this example where the head of the skull follows the cursor. However, I want ...

Issue with populating labels in c3.js chart when loading dynamic JSON data

Received data from the database can vary in quantity, ranging from 3 to 5 items. Initially, a multi-dimensional array was used to load the data. However, when the number of items changes, such as dropping to 4, 3, 2, or even 1, the bars do not populate acc ...

Guidance on incorporating a function as a prop in React using TypeScript

I'm currently learning TypeScript with React and ran into an issue. I attempted to pass a function as a property from my App component to a child component named DataForm. However, I encountered the following error: Type '(f: any) => any&ap ...

The occurrence of events for a basic model in Backbone is inexplicably non

I attempted to save some model data on localStorage (and even tried to catch this event and log some text to the console), but it didn't work - no errors and no events either. Here is my JavaScript code: var app = { debug: true, log: func ...

Transmit an audio buffer to the client for direct download without the need for server storage

As part of my project, I am developing a text-to-speech feature utilizing the technology of IBM Watson API. With the assistance of the code snippet below, I have successfully managed to acquire the .wav file after conversion onto my server. textToSpeech ...

Applying multiple select filters in AngularJS to refine a scope

Check out my fiddle example here: http://jsfiddle.net/mwrLc/12/ <div ng-controller="MyCtrl"> <select ng-model="searchCountries" ng-options="cc.country for cc in countriesList | orderBy:'country'"> <option value="">Country ...

Navigating to the parent node in a treeview within the wijmo flex grid: a step-by-step guide

Utilizing the wijmo flex grid, I've successfully created a tree view for my data. I can determine if a specific node has children and its level, but I'm struggling to navigate to the parent node from a given one. Additionally, I am able to retrie ...

Retrieve the current date in the format of dd/mm/yyyy using AJAX request

var currentDate = new Date(); var todayDate = currentDate.getDate() + '/' + monthNames[currentDate.getMonth()] + '/' + currentDate.getFullYear(); This is my current date retrieval method. It works well but has a minor issue. For to ...

I'm looking for an easy way to generate a special effect when my mouse interacts with a div using HTML, CSS, or JavaScript

I'm attempting to replicate this interesting effect where a div is surrounded by a container when the mouse hovers over it. It looks pretty cool, like in this image here: https://i.stack.imgur.com/p0epq.png Does anyone have any suggestions on how I ...

How can I effectively hide the headMenu in a different controller?

I need assistance with hiding my headmenu in the application. app.controller("kpiOverviewCtrl", function ($scope, $stateParams,) { "use strict"; var setUpController = function () { $scope.headmenu = $state.current.controller === "kpiCompareCtr ...

Retrieving Information from Website Database

My goal is to import data from a web query into Excel. However, I am facing a challenge with the IP address (e.g., 10.10.111.20) because it only displays page 1 with 20 rows of entry data. When I try to navigate to page 2 or beyond, the data does not updat ...

Storing a collection of images simultaneously in Firebase Storage and saving their URLs in a Firestore document using Firebase v9

I am currently working on a form that requires users to input data in order to generate a detailed city document. Additionally, users must upload multiple photos of the city as part of this process. Once the form is submitted, a new city document is create ...