Executing a series of promises sequentially and pausing to finish execution

I have been attempting to run a loop where a promise and its respective then method are created for each iteration. My goal is to only print 'Done' once all promises have been executed in order. However, no matter what I try, 'done' always gets executed before the 'rendering's! I understand that this may seem like a repetitive issue, but so far, none of the solutions have worked. Could it be that adding a promise and a then for each iteration is causing the problem?

        let p = Promise.resolve<void>()
        for (let i = 0; i < data.results.length; i++) {
            p = p.then(_ => template.instantiateToElement(data.results[i]).then(res => {
                console.log('rendering');
            }));
        };
        p.then(_ => {
            console.log('done');
        });

** template.instantiateToElement() returns a promise

Answer №1

The issue arises when you execute instantiateToElement() after the loop has finished running, causing it to only recognize the final value of i, which is data.results.length.

A more effective approach would be to utilize a function to capture the correct value of i:

const instantiate = (i) => (_ => template.instantiateToElement(data.results[i]));
let p = Promise.resolve<void>();
for (let i = 0; i < data.results.length; i++) {
    p = p.then(instantiate(i)).then(res => {
        console.log('rendering');
    }));
}
p.then(_ => {
    console.log('done');
});

By calling instantiate(i) within the loop, a new closure is created to bind the specific value of i.

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

Is it possible to obtain the URL (including parameters) of the first navigation before proceeding with the navigation process?

My goal is to automatically navigate to a specific website when a certain condition for the URL is met. Consider the following scenario in the ngOnInit() method of app.component.ts: if (urlMatchesCondition()) { await this.router.navigateByUrl('sp ...

Issue with Angular/Jasmine: Undefined property 'pipe' not readable

I have been struggling to resolve a problem with Angular 9, Jasmine, and RxJS without much success. While my unit tests run successfully in Jasmine, there are certain lines of code that do not get executed. Despite scouring multiple posts for assistance, ...

What steps can be taken to avoid an abundance of JS event handlers in React?

Issue A problem arises when an application needs to determine the inner size of the window. The recommended React pattern involves registering an event listener using a one-time effect hook. Despite appearing to add the event listener only once, multiple ...

Displaying a child component as a standalone page rather than integrating it within the parent component's body

I'm currently working on implementing nested navigation in my website, but I am facing challenges with loading the child component without the need to include a router-outlet in the parent component. This setup is causing the child component's co ...

What could be causing React to generate an error when attempting to utilize my custom hook to retrieve data from Firebase using context?

Currently, I am restructuring my code to improve organization by moving data fetching to custom hooks instead of within the component file. However, I am encountering issues with the hook not functioning properly when used in conjunction with my context. ...

Utilize Material-UI in Reactjs to showcase tree data in a table format

I am currently tackling a small project which involves utilizing a tree structure Table, the image below provides a visual representation of it! click here for image description The table displayed in the picture is from my previous project where I made ...

The Element is Unfamiliar - Application with Multiple Modules

I seem to be facing an issue with how my modules are structured, as I am unable to use shared components across different modules. Basically, I have a Core module and a Feature module. The Core module contains components that I want to share across multip ...

Special attribute assigned to the response object of HTTP

Is there a recommended way to add custom values to the response object? I find myself in a situation where I am using promises and can only return one value, but I need to include both the body and response objects. I attempted creating an object in this ...

Why am I receiving the error message "Argument of type 'number' is not assignable to parameter of type 'never'?"

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { showSecret = false; logArr ...

Error: Local variable remains undefined following an HTTP request

Whenever I make http calls, my goal is to store the received JSON data in a local variable within my component and then showcase it in the view. Service: getCases(){ return this.http.get('someUrl') .map((res: Response) => res.jso ...

What is the best way to update a deeply nested array of objects?

I have an array of objects with nested data that includes product, task, instrument details, and assets. I am attempting to locate a specific instrument by supplier ID and modify its asset values based on a given number. const data = [ { // Data for ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

The base URL specified in the tsconfig file is causing the absolute path to malfunction

Displayed below is the layout of my folders on the left, along with a metro error in the terminal and my tsconfig.json configuration with baseUrl set to './src'. Additionally, I have included screenshots of my app.ts and MainTabs.ts for further c ...

What is the correct way to type this object conversion?

I'm trying to ensure type safety for a specific converting scenario. The goal is to map over the palette object and convert any entries to key-value pairs, similar to how tailwindcss handles color configurations. However, I am facing an issue where th ...

Craft a unique typings file tailored to your needs

After recently creating my first published npm package named "Foo", I encountered some difficulties while trying to consume it in a TypeScript project. The tutorials on how to declare modules with custom typings were not clear enough for me. Here are the k ...

Error encountered by Angular's Injector in the AppModule when attempting to access the HttpHandler component

I have been successfully running an app for the past few months with no issues. Now, I am exploring the idea of moving some common services into a library that can be utilized by other applications. For this project, I decided to avoid using Angular CLI t ...

What is the best way to monitor updates made to a function that utilizes firestore's onSnapShot method?

I am currently working with the following function: public GetExercisePosts(user: User): ExercisePost[] { const exercisePosts = new Array<ExercisePost>(); firebase.firestore().collection('exercise-posts').where('created-by&apo ...

Understanding how to use TypeScript modules with system exports in the browser using systemjs

I’m facing an issue while using systemjs. I compiled this code with tsc and exported it: https://github.com/quantumjs/solar-popup/blob/master/package.json#L10 { "compilerOptions": { "module": "system", "target": "es5", "sourceMap": true, ...

When using VS Code, custom.d.ts will only be recognized if the file is currently open in the

I have created some custom Typescript declarations in a custom.d.ts file. When I have this file opened in VS Code, everything works correctly and the types are recognized. However, when I close the file, VS Code does not recognize these definitions, leadin ...

The orderBy filter seems to be malfunctioning

I'm utilizing ngx-pipes from this webpage: https://www.npmjs.com/package/ngx-pipes#orderby Specifically, I am using the orderBy pipe. However, when I implement the orderBy pipe in my HTML, the information is not being ordered correctly (from minor t ...