Looping through Angular promises sequentially

I am faced with a dataset consisting of the following information.

 $scope.orders = [
        { material: 'A', quantity: 32, orderNumber: 'dummy'},
        { material: 'A', quantity: 65, orderNumber: 'dummy'},
        { material: 'A', quantity: 86, orderNumber: 'dummy'},

        { material: 'B', quantity: 45, orderNumber: 'dummy'},
        { material: 'B', quantity: 68, orderNumber: 'dummy'},
        { material: 'B', quantity: 15, orderNumber: 'dummy'},

        { material: 'C', quantity: 11, orderNumber: 'dummy'}
    ];

The challenge I am facing is processing (createOrder) these orders grouped by their respective materials. Once all the orders for a particular material have been processed, I need to trigger another function (materialRun) that executes a material run. This needs to be done sequentially as the backend system cannot handle parallel processing.

I envision the process to flow like this:

Material A: Order 1 -> Order 2 -> Order 3 -> Material Run

Once the Material Run for A is complete, move on to Material B

Material B: Order 1 -> Order 2 -> Order 3 -> Material Run

Once the Material Run for B is complete, proceed to Material C

...and so on

Furthermore, I require the output from each createOrder operation to update the orders list dynamically.

Currently, I am utilizing angular promises, but I am open to alternative approaches and suggestions. For reference, you can view an example in this fiddle: http://jsfiddle.net/a1sp0ye2/

Answer №1

Here is a method for looping through items asynchronously when each iteration depends on the completion of an asynchronous task. This template is specifically designed for promises in Angular, but can be adapted for use with any promises implementation:

/**
 * Perform asynchronous looping through an array.
 *
 * @param items - Array to iterate
 * @param doLoopBody - Callback function to execute for each iteration, returns a promise
 */
function asyncLoop(items, doLoopBody) {
    var i = 0, d = $q.defer();

    nextIteration();

    return d.promise;

    function nextIteration() {
        if( i < items.length ) {
            doLoopBody(items[i], i, items).then(
                function() {
                    i++;
                    nextIteration();
                },
                onError
            );
        }
        else {
            d.resolve();
        }
    }

    function onError(reason) {
        d.reject(reason);
    }
}

You can view a basic implementation based on this approach here (check the browser's console for output).

Answer №2

Although I'm not entirely certain if this will solve your issue, you can give my code a try:jsfiddle

        $scope.promises = [];
        ordersByMaterial.forEach(function(order) {
            $scope.promises.push(createOrder(order));
        });

I decided to test it out by creating $scope.logsCreateValue = []; and storing random values using Math.floor(Math.random() * 10); Make sure to check the output in the

console.log($scope.logsCreateValue);
, it should correlate with the values set by
$scope.orders[key].orderNumber = res[key].orderNumber;

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

Storing Data in Session Storage Post Page Redirection (utilizing AngularJS Routing)

In my current setup, I am facing a situation where the login page will eventually transition to the SAML2 identity provider server upon successful authentication, followed by a redirection to another server hosting the main application. To facilitate test ...

When $(.class) displays result, Javascript ceases execution

In the code snippet below, I am trying to load a group of products from a category when the user clicks on the .expandproducts button: $('.expandproducts').click(function(){ id = $(this).attr("data-id"); urlajax = document.location.origi ...

Managing API calls through Next.js routing

Here is a next.js handler function for handling api requests on our server. I am looking for assistance on how to access a variable between request methods. Any help would be greatly appreciated. export default function handler(req, res) { if(req.met ...

A guide on using Sinon to mock a custom $http transform

Exploring the proper method for mocking an http post with a custom transform in Angular using the Sinon mocking framework. In my CoffeeScript Sinon unit test setup, I define mocks like this: beforeEach module(($provide) -> mockHttp = {} $provide.value ...

Error in HTML: The AgGrid component is missing the required 'col' attribute

Initially, I worked with the 2.3.5 version of Ag-Grid which had a "col" attribute showing the relative index of the column for each cell element. The "row" attribute still remains unchanged. However, after upgrading to version 4.0.5, the "col" attribute ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

Leverage jQuery to Retrieve Text and Modify

My Content Management System automatically generates a time stamp for when a page was last updated. However, the format it provides is not ideal for my needs. I would like the date to be displayed in the US Standard way - May 24, 2013, without including th ...

Looking to streamline a JavaScript function, while also incorporating jQuery techniques

I've got this lengthy function for uploading photos using hidden iFrames, and while it does the job well, it's quite messy. I'm looking to simplify it into a cleaner function with fewer lines of code for easier maintenance. function simplif ...

Combining Vue.js with Laravel Blade

I've encountered an issue while trying to implement a Basic Vue script within my Laravel blade template. The error message I am getting reads: app.js:32753 [Vue warn]: Property or method "message" is not defined on the instance but referenc ...

"Oops! Vite seems to be facing an issue as RefreshRuntime.injectIntoGlobalHook function is

Our CRA react app has been transitioned from webpack to Vite. Problem: When running the application locally in production mode, I encounter the following error: 1. Uncaught TypeError: RefreshRuntime.injectIntoGlobalHook is not a function at (index):6:16 ...

Execute asynchronous functions without pausing the thread using the await keyword

When working with an express route, I need to track a user's database access without: waiting for the process to complete before executing the user's task worrying about whether the logging operation was successful or not I'm uncertain if ...

Receiving a k6 response that includes a JSON object with a lengthy integer value

During a performance test, I encountered an issue where the response contained items like: {"item":{"id":2733382000000000049}} When parsed using k6's response.json(), it appeared as : {"item":{"id":273338200000 ...

Upon pressing enter in the input box, the page will redirect to localhost:3000/

Utilizing the NewYorkTimes API to retrieve search queries from an input field. However, upon hitting enter after entering a query, my localhost reloads and redirects to localhost:3000/?. After using console.log(url) in the console, I confirmed that the UR ...

Determine image size (pre-upload)

One of the requirements for a project I am working on is to verify the dimensions (width and height) of images before uploading them. I have outlined 3 key checkpoints: 1. If the dimensions are less than 600 X 600 pixels, the upload should be rejected. ...

Nesting / Mulled / JS - Uploading Files - Form's end is unexpectedly reached

I have successfully implemented the upload file functionality in my Nest.js server application, but I am facing an issue when trying to use it with JavaScript/React. @Post('upload') @UseInterceptors(FileInterceptor('file')) upl ...

Switching out the background image with a higher resolution one specifically for users with retina devices

I'm trying to create my very first website that is retina ready, but I've run into an issue when it comes to updating images to higher resolutions in CSS. I'm unsure how to go about having a standard image as the background and then switchin ...

Ensure that each child component receives a prop

Can you transfer a prop with a function to any child component? Specifically, I want to send a function from a parent component to each {children} element: <> <Navbar /> <main>{children}</main> <Footer /> </&g ...

What are the best methods for profiling a Node.js application at a specific point in its execution?

I am currently facing performance issues with my Node application, which listens to a websocket data feed and communicates with another API. The CPU usage is normally stable at around 2-5%, but occasionally (approximately 3 times within 24 hours) the incom ...

The view displays a true boolean value, while the controller is returning a false boolean value in

Within the parent scope (the external one that wraps the entire webapp), a boolean variable is defined to check if the user is logged in. $localForage.getItem('authorization') .then(function(authData) { if(authData) { ...