Wait for each observable subscription to complete

In my scenario, I have an array called orderCodes, which stores specific order codes. With each code, I can retrieve the corresponding order details, where each order contains multiple products. My goal is to extract the code of each product from the order details.

The function getOrderDetails() returns an Observable containing the results (an array of products). Each individual result has a code property that holds the necessary information.

this.orderCodes.forEach((orderCode) => {

  loadOrderDetails(orderCode);

  getOrderDetails().subscribe((order: any) => {
    if (order.results) {
      order.results.map((result) => {
        console.log(result.code);
      });
    }
  });

});

I attempted using this forEach loop, but due to subscribing to an Observable, the loop moves on to the next iteration before waiting for the previous one to complete. As a result, the desired output is not achieved.

Do you have any suggestions or solutions?

Answer №1

One way to approach this with RxJS is:

from(this.orderCodes).pipe(
  concatMap((orderCode) =>  // Using concatMap to maintain order of items
    defer(() => {
      loadOrderDetails(orderCode);

      return getOrderDetails();

    }))
).subscribe((order: any) => {
  if (order.results) {
    order.results.map((result) => {
      console.log(result.code);
    });
  }
});

Alternatively, you could handle it using promises and async/await:

async myFunctionThatDoesAllThis(...) {
....
for(let orderCode of this.orderCodes) {
  loadOrderDetails();
  const order = await getOrderDetails().pipe(take(1)).toPromise(); // Skip pipe(take(1)) if getOrderDetails is just an http request.
  if(order.results) {
     order.results.forEach((result) => {
        console.log(result.code);
     });
  }
}

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

Steps to creating a popup within an HTML page from another HTML page

I recently started learning JavaScript. I have a link on my homepage that directs to another HTML page, but I would like it to show as a popup on the homepage with responsiveness and some stylish design elements such as a folded corner. Is there a way to a ...

Using the ASP.NET parameter or variable in both the application settings and application build events

Is it possible to retrieve an Application Setting from the Pre Build Event in ASP.NET? Can the value of a Setting be injected from the Pre Build Event? Here is the full context: In my project, I have an Angular app integrated within an ASP.NET 4 Web API ...

Is it possible to load JavaScript code once the entire page has finished loading?

My webpage includes a script loading an external JavaScript file and initiating an Ajax query. However, the browser seems to be waiting for example.com during the initial page load, indicating that this external dependency may be causing a delay. Is there ...

Reconfigure an ancestral item into a designated key

I have a single object with an array of roles inside, and I need to transform the roles into an array of objects. See example below: Current Object: displayConfiguration: { widgetList: { widgetName: 'widget title', entityType: 'As ...

Executing a PHP function within the same file using AJAX: A step-by-step guide

I've been exploring online tutorials to learn about ajax as it's a new technology for me. My main goal is to understand how to utilize two functions, create() and population(), in a php file. The create() function generates a form like this: ma ...

What is the best way to use jQuery to retrieve information from one child element in an XML API in order to locate another child

Hi there, I'm new to jQuery and could use some help. I'm attempting to retrieve specific information like CPU and RAM details from a particular phone model. I've written the jQuery code, but I'm having trouble displaying the RAM and CPU ...

Sending an interface object to a custom component using ngFor

I'm facing a challenge with this task. The child component I'm working on includes the following: ChildComponent @Input() record : InterfaceRecord; Where InterfaceRecord is defined as: export interface InterfaceRecord { ti ...

The functionality of two-way data binding seems to be failing in Angular 2

I encountered an issue in my Angular 2 application where I attempted to bind view data using ngModel, but it did not function as expected. event.component.html <div class="form-group"> <label for="comment">About Us:</label> ...

What is the functionality of input onChange in React when using state management?

Whenever I try to log the value of the input after each onChange event, there seems to be an odd one event delay. For example, if 'some text' is the default input value and I remove the letter 't' by pressing backspace/delete, it first ...

What is the best way to retrieve a service response prior to component initialization in Angular 4?

My service sends a request to an API, and based on the response, I need to decide whether a component should be loaded or not. However, due to the delay in receiving the response, the component loads regardless of the response status. After about 0.5 secon ...

Replace existing styled-component CSS properties with custom ones

One of my components includes a CheckBox and Label element. I want to adjust the spacing around the label when it's used inside the CheckBox. Can this be achieved with styled()? Debugging Info The issue seems to be that the className prop is not b ...

Stop the animation when the mouse is moved

Below is the code I am working with: $(source) .on('mouseenter', start) .on('mouseleave', stop) .on('mousemove', zoom.move); Within this code, I have attached several mouse event listeners. When the 'mouseenter' ev ...

Issue with Mongoose Promise failing to transfer data to the following chain

When querying MongoDB using mongoose with promises, I encounter an issue where the result is only accessible in the initial .then(function(results){ // can send the result from here..}). However, when I manipulate the results and attempt to pass them to th ...

Utilize Webpack to integrate redux-form as an external library

I currently have a range of imports in my project, such as: import {Field, reduxForm, FormSection, formValueSelector} from 'redux-form'; My goal is to treat the redux-form imports as an external library so that they do not get included in the b ...

Utilize an exported class as a type within a .d.ts file

I have two classes, ./class1.ts and ./class2.ts, with the following structure: export class Class1{ ... } and export class Class2{ ... } In my file ./run.ts, there is a function that accepts a class input function doSomething(klass: ClassType){ l ...

Can you assist me in deciding between Javascript, jQuery, or AJAX?

As I embark on my JavaScript learning journey, I am faced with the decision of whether to focus on jQuery and Ajax. Although both are JavaScript frameworks, I am unsure of which one would be the best fit for me. I know HTML, CSS, PHP, and MySQL, and my m ...

What is the method for instructing the Typescript compiler to process JSX within .ts files?

My .ts files contain .jsx syntax, and I am looking to instruct tsc on how to compile them the way it compiles .tsx files. Is there a way to adjust the configuration of tsc to achieve this? Additionally, are there steps to configure vscode for proper synt ...

Tips for implementing two functions to run within the onClick event handler in React

I am looking to simultaneously execute two functions handleClose and saveData within the onClick method. The specific location where I want this execution to happen: <Button variant="contained" onClick={saveData}&g ...

Button to scroll down

I have successfully implemented a #scrolldownbutton that scrolls to the first component. However, I am now attempting to modify it so that when the button is clicked, the page smoothly scrolls within the viewport and stops at the partially visible componen ...

Utilizing a responsive design with a bootstrap grid system, featuring expandable columns for

After creating a bootstrap grid page, I am facing an issue with the layout on mobile screens. My problem arises when trying to reorder the cards properly for mobile view. Here is my current logic: <div class="row"> <div *ngFor="let col of [1, ...