What is the best way to retrieve a promise from several promises?

Every time I check the console, I see the following:

  1. teamsUpdated2
  2. addUserToProjects
  3. deleteUserFromProjects

However, they should be displayed in a different order.

var result = teamService.addOrDeleteUser(userId, newTeams, deleteTeams);
result.then(function () {
     console.log("teamsUpdated2");          
     });

A function that includes multiple promises:

var _addOrDeleteUser = function (userId, addToProjects, removeFromProjects) {
    var deferred = $q.defer();
    var promises = [];

    promises.push(projectResource.addUserToProjects({ userId: userId }, addToProjects, function (result) {
        console.log("addUserToProjects");
        deferred.resolve();
        return result;
    }));

    promises.push(projectResource.deleteUserFromProjects({ userId: userId }, removeFromProjects, function (result) {
        console.log("deleteUserFromProjects");
        deferred.resolve();
        return result;
    }));

    return $q.all(promises);
}

Answer №1

To streamline your code, you can implement promise chaining like this -

travelService
       .getDeparture( user )                                           // Fetching departure information
       .then( function( departure ){
            $scope.departure = departure;                            // Handling response for departure data
            return travelService.getFlight( departure.flightID );       // Requesting flight details
        })
        .then( function( flight ){
             $scope.flight = flight;                                // Processing response for flight information
             return weatherService.getForecast( $scope.departure.date ); // Requesting weather forecast
        })
        .then( function( weather ){
            $scope.weather = weather;                               // Handling weather forecast response
        });

To learn more about promise chaining, check out this resource

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

Tips on handling a redirection request following a fetch post request

When communicating with my node server (Express) using fetch to build a Single Page Application (SPA), I have encountered an issue. Upon each request to the server, I validate the session and redirect to a login page if it is not valid. However, I noticed ...

Turn off the authentication middleware for a particular HTTP method on a specific endpoint

Currently, I am using Express/Node and have developed authentication middleware to validate JWT on each request. My requirement is to disable this middleware for a specific route (POST '/api/user/') while keeping it active for another route (GET ...

Unable to attach an onClick event handler to <TableRowColumn> element using Material-UI in React

In the past, I had a feature that allowed me to change the color of the text from red to green by clicking on a table cell. After introducing Material-UI in my React app and replacing the <td> tags with <TableRowColumn> tags, I noticed that th ...

When using `require('backbone')`, the returned object can vary depending on the file it is called in

backbone1.js var backbone1=require('backbone'); window.backbone=backbone1; backbone2.js console.log(window.backbone===require('backbone')); Why is the condition returning false. Shouldn't it return the same object everytime? E ...

What is the best practice for passing parameters to a child uiView in AngularJS?

I am working on a project with multiple states and views. angular.module('myapp', ['ui.router']).state('property', { url: '/property', views: { '': { templateUrl: 'partial/ ...

State variables in React hooks like useState always return the previous value before

Whenever I choose a value, it seems to always display the previously selected option instead of the current one. What I really want is for the selection to update and store the current value immediately. const [postsPerPage, setPostsPerPage] = useState(1 ...

The Typescript Select is displaying an incorrect value

Here's the code snippet I've been working with: <select #C (change)="changeSelect(zone.id, C.value)"> <option *ngFor="let town of townsLocal" [attr.value]="town.data" [attr.selected]="town.data === zone.town && 'selected& ...

Issues with Google Analytics Event Tracker Inconsistent Performance

I am experiencing an issue with a Google Analytics event that is triggered when a user clicks on a form submission button to enroll in a course. The event uses data attributes within the button element. What's puzzling is that the event seems to be w ...

End event in NodeJS response does not activate

I'm encountering an issue with sending the response data to the client. The response is not being sent and the 'end' event is not triggered. I'm at a loss on how to resolve this issue. My objective is to send the retrieved data from red ...

"Enhance your Magento store with the ability to showcase multiple configurable products on the category page, even when dropdown values are not

As I work on adding multiple configurable products to a category list page in Magento 1.7.2, I am facing some challenges due to using the Organic Internet SCP extension and EM Gala Colorswatches. While following tutorials from various sources like Inchoo a ...

Passport Authentication does not initiate a redirect

While working on a local-signup strategy, I encountered an issue where the authentication process against my empty collection was timing out after submitting the form. Despite calling passport.authenticate(), there were no redirects happening and the timeo ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

Using Socket.IO in Node.js to distribute information to every connected client

Currently, I am in the process of developing a WebGL multiplayer game. My approach involves using socket.io and express in node.js to enable multiplayer functionality. However, I am encountering an issue with broadcasting key events. When a user presses a ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...

Can anyone provide guidance on how to calculate the total sum of a JavaScript array within an asynchronous function?

Currently, I am working with Angularjs Protractor for end-to-end testing and faced an issue while trying to calculate the sum of values in a column. Although I am able to print out each value within the loop successfully, I am struggling to figure out ho ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

What is the best way to connect a series of checkboxes within a form utilizing Angular?

I created a form with checkboxes that allow users to select multiple options. However, when I submit the form, instead of receiving an array of objects representing the checked checkboxes, I'm not getting anything at all. Here is what I see in the co ...

What is the best way to save the data received from createApi into the Redux store?

Currently, I am faced with the challenge of storing user data (such as name, email, etc.) obtained through the createApi function into Redux store. However, I'm unsure of the best practice to achieve this. In my userApi.js file: export const userApi ...

Sending data between two elements when a jQuery event is triggered

As a JavaScript beginner, I am facing an issue where I need to push data from an h1 tag to a textarea. My website is built using WooCommerce and when a visitor clicks on a product, a chat box with the product title opens. Currently, I have successfully p ...

What is the technique for combining a string and an HTML element using literal values?

Trying to merge text with a hyperlink: const myText = `${t('privacyTxt')}` + `${<a>{t('privacyLink')}</a>}`; output: If you want to know more about our data processing, check out our[object Object] What else do I need ...