do not continue loop if promise is rejected in AngularJS

I've attempted multiple methods, but still haven't found a solution to this issue.

Within my code, there is a method called iterator that returns a promise; this method runs in a loop x number of times. If the iterator function returns a rejected promise, I want the execution to stop and proceed to the error block.

I tried implementing the solution from this SO answer, but it continues executing for all iterations despite encountering an error.

var foo = function(formdata) {
   var d = $q.defer();
   CallService.init()
  .then(function(response) {
    return CallService.fun1(formdata);
  })
  .then(function(response) {
     var row = {1:'one', 2:'two', 3: 'three' };
     var promiseArray = [];
     if (<key condition true>) {            
        var promise = Object.keys(row).map(function(i) {
            return iterator(i, row[i]).then(function(response){
                promiseArray.push(response);
                }, function(err){
                return $q.reject(err);
            });
        });
        return $q.all(promise); // reject if anyone is rejected, otherwise resolve
    }
    else {
        d.reject({
            message: "key condition failed."
        });
    }
    return d.promise;  
})
 .then(successHandler)
 .catch(errorHandler);
};

The iterator function being called in each iteration is defined as:

var iterator = function(num, data) {
    var d = $q.defer();
    CallService.fun3()
    .then(function(response) {
        return CallService.fun4(data)
    })
    .then(function(response) {
       d.resolve(num);
    })
    .catch(function(err) {           
       d.reject(err);
    });
    return d.promise;
};

The goal is to stop the loop if iterator sends a rejection on the first call, but all iterations are currently running even after an error is encountered.

I have also attempted the following approach:

var d = $q.defer();
for (var k in row) {
    if (isCalled) break;
    var promise = iterator(k, row[k]);
    promise.then(function(response) {
        promiseArray.push(response);
    }, function(err) {
        isCalled = true;
        d.reject(err);
    });
}
if (!isCalled && promiseArray.length > 0) {
    console.log('after for loop', promiseArray);
    d.resolve(promiseArray);
}

return d.promise;

Despite trying different methods, the loop executes for all iterations regardless of any rejected promises.

Edit

I explored using the .reduce method, which partially worked. However, I need to include the promiseArray along with the error when a rejection occurs. Here is the revised code snippet:

var first_promise = $q.resolve();
var start_promise = Object.keys(row).reduce(function(promise, key){
      return promise.then(function(result){
          if(angular.isDefined(result)) 
              promiseArray.push(result);
          return iterator(key, row[key]);
      });
 }, first_promise);
 start_promise.then(function(res){
     return $q.when(promiseArray);
 }).catch(function(err){
     return $q.reject();
 });

Answer №1

Revised response following clarification. The user desires their asynchronous operations to execute synchronously, halting when encountering a rejection.

Take a look at this informative article. It appears that the mentioned decorator accomplishes this precise task.

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

Create an HTML table to view JSON data from a cell on a map

Looking to transform the JSON data into a table by organizing the information based on supplier and product. Below is the JSON input and code snippet: $(document).ready(function () { var json = [{ "Supplier": "Supplier1", "Product": "O ...

What steps can be taken to ensure that a function is executed in order to delegate the process forward?

In my JavaScript code, I have a series of functions that need to be executed in a specific order. One function may return a value synchronously, while others do not return anything or return an Observable result asynchronously. How can I ensure that each ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

Fixing a menu hover appearance

I recently encountered a small issue with the menu on my website. When hovering over a menu item, a sub-menu should appear. However, there seems to be a slight misalignment where the submenu appears a few pixels below the actual menu item. Check out the w ...

Is there a way to retrieve a promise from a function that triggers a $http.get request in AngularJS?

Looking for a solution to modify this function: getX: function ($scope) { $http.get('/api/X/GetSelect') .success(function (data) { ... ... }) .error(function (data) { ...

The TypeScript datatype 'string | null' cannot be assigned to the datatype 'string'

Within this excerpt, I've encountered the following error: Type 'string | null' cannot be assigned to type 'string'. Type 'null' cannot be assigned to type 'string'. TS2322 async function FetchSpecificCoinBy ...

Develop a Vue mixin to enable theme switching in a Vue.js application

I have successfully developed three distinct themes: light, default, and dark. Currently, I am working on implementing a toggle function in the footer section that allows users to switch between these themes effortlessly. Following the guidance provided b ...

Leveraging a VueJS prop as a variable in an array mapping operation

Trying to figure out a solution where a variable (prop) can be used in an array map function. The initial code snippet looks like this: var result = this.$store.getters['example/store'].map(a => a.fixed_column) I aim for fixed_column to be ...

Is there a way to activate the width styling from one class to another?

I have these 2 elements in my webpage: //1st object <span class="ui-slider-handle" tabindex="0" style="left: 15.3153%;"></span> //2nd object <div id="waveform"> <wave style="display: block; position: relative; user-select: none; he ...

I have a json file that I need to convert to a csv format

I am currently working with a json file, but I need to switch it out for a csv file. Do I have to use a specific library to accomplish this task, or can I simply modify the jQuery 'get' request from json to csv? I attempted the latter approach, b ...

Guidance on implementing fallback font formats using FontFace API

I am exploring the FontFace API (not @fontface) and wondering if there is an easy way to include multiple font formats, similar to providing multiple sources in @fontface. Alternatively, is there a simple method to identify which font formats are supporte ...

Issue encountered in Angularjs during upgrade process from version 1.2.27 to 1.4.7

Recently, I upgraded my app from using AngularJS 1.2.27 to version 1.4.7, but now I am encountering an error in the AngularJS file. SyntaxError: Unexpected token : (angular.js:12477) at Function (native) at Object.sd. ...

Connecting Vue component data to external state sources

I am facing a challenge with integrating a Vue component into a large legacy system that is not based on Vue. This component retrieves data through AJAX requests and displays information based on an array of database record IDs, typically passed at page lo ...

Uncovering the Mystery of Undefined Dom Ref Values in Vue 3 Templaterefs

I am currently experimenting with the beta version of Vue 3 and encountering an issue while trying to access a ref in the setup function. Here is my component: JS(Vue): const Child = createComponent({ setup () { let tabs = ref() console.log(t ...

What is the best way to retrieve the canonicalized minimum and maximum values within the beforeShow method of jQuery UI's datepicker?

I have a pair of datepicker elements that I want to function as a range. When a value is set in the "low" datepicker, it should adjust the minDate and yearRange in the other datepicker, and vice versa with the "high" datepicker. The challenge I'm faci ...

Tips for effectively utilizing innerHTML in this particular scenario

For an assignment, we were tasked with creating a Madlib game where users input words into textfields to replace certain words in a hidden paragraph within the HTML using JavaScript and CSS. The paragraph embedded in the HTML page is as follows: <span ...

What could be causing my ASP.Net MVC script bundles to load on every page view?

I'm a bit puzzled. The _layout.cshtml page I have below contains several bundles of .css and .js files. Upon the initial site load, each file in the bundles is processed, which makes sense. However, every time a new view is loaded, each line of code f ...

Transforming NodeJS Express HTTP responses into strings for AngularJS consumption

I have been working on creating an AngularJS program that communicates with an Express/Node.js API and a MySQL database. On the login page, I am successfully able to call the API which connects to MySQL. Depending on the correct combination of username an ...

issue with cordova-plugin-geolocation functionality on Android mobile device

Having trouble with the cordova-plugin-geolocation plugin in my ionic/cordova app. It functions perfectly on my browser and iOS device, but when I try it on Android, the map fails to display and does not acquire GPS coordinates. Instead, it times out and t ...

Preserve object properties while allowing for changes to be made without affecting

I am in need of transferring specific properties from one object to another while ensuring that the original object remains mutable. Here is the original object: var sourceObject = { "key1": "value1", "key2": "value2 ...