How to wait for async code before continuing [duplicate]

Discussão em 'Angular' iniciado por TheIronCheek, Abril 18, 2025.

  1. TheIronCheek

    TheIronCheek Guest

    I have the following code:

    var myInvoices: Invoice[] = new Array<Invoice>();
    var tasksToRun = new Array();

    items.forEach(async (item) => {
    await this.http.get(`/api/Timesheets` + item[0]).pipe()
    .subscribe(async (result) => {
    if (result.Amount > 0) {
    var inv: Invoice = new Invoice(0);

    inv.value = item[1];
    myInvoices.push(inv);
    }
    });
    });

    console.log("myInvoices:", myInvoices); //outputs the contents of several invoices to the console
    this.http.post(`/api/invoices`, myInvoices); //error due to an empty body


    My API is returning an error saying


    A non-empty request body is required
    ​

    If I use console.log() to display the contents of myInvoices, I can see that there are several invoices in the array which I believe tells me that the POST request is running before the code inside the .forEach() finishes and myInvoices is populated.

    How can I ensure that everything inside the .forEach() is done before running the POST request?

    Continue reading...

Compartilhe esta Página