Is there a way to ensure that a promise is only executed once the previous promise has been resolved?

How can I make 2 HTTP requests in AngularJS where the second request is only executed after the first one has been resolved? Also, I need both requests' returns simultaneously. What is the best approach for achieving this?

I attempted to tackle this issue with the code provided below, but both promises are being executed concurrently. How can I ensure that the second promise is only triggered once the first promise resolves?

$q.all([
    getData(api_url('categories')),
    getData(api_url('tags')), // This promise must only be executed after the promise above has been resolved
]).then(function (response) {
    $scope.categories = response[0];
    $scope.tags = response[1];
}).catch(function (error) {
    notify('Cannot get data for articles register!', 'error');
});

[UPDATE] I found a solution using the code below, but I don't think it's the most optimal way to handle this situation. How can I enhance this code further?

getData(api_url('categories')).then(function (response) {
    categories = response.data;
    return getData(api_url('tags')).then(function (response) {
        tags = response.data;
        $scope.categories = categories;
        $scope.tags = tags;
    });
}).catch(function (response) {
    notify('Cannot get data for articles register!', 'error');
});

[SOLUTION]

var categoriesPromise = getData(api_url('categories'));
var tagsPromise = categoriesPromise.then(function (response) {
    return getData(api_url('tags'));
});

$q.all([categoriesPromise, tagsPromise]).then(function (response) {
    $scope.categories = response[0].data;
    $scope.tags = response[1].data;
}).catch(function (response) {
    notify('Cannot get data for articles register!', 'error')
});

Answer №1

Could this possibly be an improvement?

fetchDataFromEndpoint(api_url('categories'))
  .then(function(result) {
    $scope.categories = result.data;

    return fetchDataFromEndpoint(api_url('tags'));
  }).then(function(result) {
    $scope.tags = result.data;
  }).catch(function(error) {
    displayErrorNotification('Unable to retrieve data for articles registration!', 'error');
  });

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

Utilizing jQuery with the themoviedb JSON API

Attempting a seemingly simple task here - extracting input from a text field and using it to search the themoviedb.org database via the API. With jQuery and themoviedb.org APIv3 in use (JSONP supported), all I'm getting in return is the following res ...

Sending information to a Google spreadsheet using JavaScript executed in a web browser

Currently, I am developing a web application that requires the user to be able to upload data directly to their own Google spreadsheet. Initially, I attempted to utilize the Google APIs Client Library for JavaScript but found that it does not include supp ...

Creating components in React with CSS styling

After developing a component using React, I managed to use Babel to build it into the lib directory successfully. However, when it comes to building my CSS, I find myself at a loss and in need of assistance. Any help would be greatly appreciated. Thank yo ...

Navigating back to the beginning of the webpage following the completion of a form submission utilizing Master Pages and Ajax

I am having an issue with my ASP.NET 4.0 page where I want to reset it to the top after a form submission so that the validation summary can be displayed properly. The setup involves using Ajax and a master page with the following simplified code: <f ...

Apache 2 rewrite rules tailored for implementation with AngularJS

It seems like there are countless discussions and explanations about mod rewrite scattered across the internet. However, I'm struggling to wrap my head around them. That's why I decided to reach out here for some assistance. I am seeking rewrite ...

Guide on using Ajax to transmit data to Struts2 action class

In my Struts2 web application, I have the following files: member.jsp: <script type="text/javascript"> String str1 = "aaa"; String str2 = "bbb"; xmlhttp.open("GET", "http://localhost:8080/project/editprofile.action", true); xml ...

Trouble with using the date pipe in Angular specifically for the KHMER language

<span>{{ value | date: 'E, dd/MM/yyyy':undefined:languageCode }}</span> I am facing a challenge where I need to identify the specific locale code for the KHMER language used in Cambodia. Despite trying various cod ...

What is the best way to verify the presence of a value in an SQL column?

I need to check if a value exists in a column. If the value already exists, I do not want to insert it into the table. However, if it does not exist, then I want to add new data. Unfortunately, my attempted solution hasn't been successful. You can fi ...

Assign a role to the author of a message in Discord using Discord.js

I have been working on a command that assigns a role to the message author when they enter the command. However, I keep encountering an error saying "Cannot read property of 'add' of undefined". Here is the code snippet: case 'ticket': ...

JavaScript causes iPad and iPhone browsers to crash while loading images

I'm currently working on constructing an image gallery in Safari that mirrors the iPad photo app. Everything is functioning smoothly, but once I exceed around 6MB of images either by adding them to the DOM or creating new Image objects, the loading of ...

What is the best way to deal with a "Access to restricted URI denied" error in JavaScript while utilizing XMLHttpRequest?

Here is some code I am working with: var req = new XMLHttpRequest(); req.onload = function(){ if (req.status === "200"){ doSomethingWithTheReceivedData(); } else { alert("Error msg"); } }; When running index.html directly ...

Upon initial startup, the "Get Authenticated" process gets stuck in an endless loop

Upon initially loading my AngularJS application, I am faced with a blank screen and an endless loop attempting to verify the user's authentication status. For this specific project, I have opted for sails version 0.11.0 as well as the latest version ...

Some sections of the HTML form are failing to load

I'm currently following a tutorial and applying the concepts to a Rails project I had previously started. Here's my main.js: 'use strict'; angular.module('outpostApp').config(function ($stateProvider) { $stateProvider.sta ...

Tips for transferring state between functions and classes in reactjs

I'm currently utilizing hooks and have a function that makes use of the dropzone library: export function UploadFile() { const [files] = useState([]); return ( <MaterialDropZone files={files} sh ...

Display a React Native modal within another modal

Is it possible to open a modal from within another modal in react native? For example, if I have a form in one modal and a color picker field within that form, how can I open the color picker in a separate modal? Name: XYZ Age: 21 Color: A (Clicking thi ...

Struggling with passing attributes to an AngularJS directive? You might be encountering the frustrating issue of receiving undefined values for

Currently, I am working on a directive that has four parameters being passed to it, all of which are bound to the directive scope. The problem I am facing is that despite the data existing and being loaded, the directive is receiving all values as undefin ...

Utilizing Captcha with Meteor's accounts-ui-bootstrap-3 for enhanced security

Is it possible to incorporate Captcha verification when utilizing the combo of Meteor packages accounts-ui-bootstrap-3 and accounts-password? What is the process for integrating a package such as captchagen with accounts-ui? ...

Reset an Angular form after it has been submitted

I'm facing some difficulties in clearing the form after submission. Can someone guide me on how to clear the form upon submission? HTML <form id="contact" class="contact-form" ng-submit="sendMail()" novalidate ng-controller="QuoteCtrl"> <di ...

Understanding JavaScript's JSON Path Variables

I've scoured the internet for solutions to a similar issue but haven't been able to find any helpful information yet. My current challenge involves accessing a picture path (in JSON format) based on the material type of the selected element. Her ...

When attempting to retrieve the value of my select element, I encounter difficulty due to a hidden field that only becomes visible when a certain option is selected

I have a dropdown menu with different options, including one labeled "other". When the user selects "other", a hidden text field appears for them to enter a custom value. This functionality works correctly. However, if the user selects any other option and ...