Using `window.location.href` will terminate any pending asynchronous calls to the API

Before all async calls to the API are completed, window.location.href is triggered when the code runs. Setting a breakpoint on the location resolves the issue.

How can I ensure that all calls are finished before invoking window.location.href?

Code:

const saveInvoice = async () => {
    if (containsItems()) {
        let customerId = document.getElementById("Customer").value;
        let date = document.getElementById("Date").value;
        let dueDate = document.getElementById("DueDate").value;
        let msgKID = document.getElementById("MSG").value;
        let accountId = document.getElementById("Account").value;
        let data = await WebRequest("InvoiceAPI", "CreateInvoiceAsync", null, { "CustomerId": customerId, "Date": date, "DueDate": dueDate, "MsgKID": msgKID, "AccountId": accountId });

        getLineNumbers().forEach(async (nr) => {
            let prodId = parseInt(document.querySelector('select.prod[data-id=\"' + nr + '\"]').value);
            let descr = document.querySelector('input.description[data-id=\"' + nr + '\"]').value;
            let price = parseFloat(document.querySelector('span.price[data-id=\"' + nr + '\"] > span.sum').innerHTML);
            let mva = parseInt(document.querySelector('span.mva[data-id=\"' + nr + '\"] > span.sum').innerHTML);
            let mvaSum = parseFloat(document.querySelector('input.mva-value[data-id=\"' + nr + '\"]').value)
            let count = parseInt(document.querySelector('input.count[data-id=\"' + nr + '\"]').value);
            let perc = parseInt(document.querySelector('input.perc[data-id=\"' + nr + '\"]').value);
            let sum = parseFloat(document.querySelector('#Lines > div.line.row > div.amount-wrap[data-id=\"' + nr + '\"] span.line-sum').innerHTML);

            await WebRequest("InvoiceAPI", "CreateInvoiceLineAsync", null, { "InvoiceId": data.json.id, "ProductId": prodId, "Description": descr, "Count": count, "Discount": perc, "Price": price, "Mva": mva, "MvaSum": mvaSum, "Sum": sum });
        });

        window.location.href = "View/" + data.json.uId;
    }
    else {
        document.getElementById("InvoiceErrorWrap").classList.remove("hide");
    }
};

Answer №1

If you need to ensure that an array of Promises is completed, you can utilize Promise.all. Remember that Array#forEach isn't designed for handling Promises.

To generate an array with a Promise for each item returned by getLineNumbers(), you can employ Array#map.

await Promise.all(getLineNumbers().map(async nr => {
    // additional code...
    await WebRequest("InvoiceAPI", "CreateInvoiceLineAsync", null, { "InvoiceId": data.json.id, "ProductId": prodId, "Description": descr, "Count": count, "Discount": perc, "Price": price, "Mva": mva, "MvaSum": mvaSum, "Sum": sum });
}));
// set the location here

Answer №2

Each separate asynchronous task seems to be using the internal await feature, yet there is no overarching process waiting for all of these tasks to complete. In essence, even though saveInvoice is marked as async, it does not actually wait for any other operations.

To streamline the code, you can swap out the .forEach() method with the .map() method in order to generate an array of promises:

const promises = getLineNumbers().map(async (nr) => {
  //...
});

Afterwards, await the completion of these promises:

await Promise.all(promises);
window.location.href = "View/" + data.json.uId;

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

What could be the reason my Angular interceptor isn't minified correctly?

I have come across this interceptor in my Angular project: angular.module('dwExceptionHandler', []) .factory('ExceptionInterceptor', ['$q', function ($q) { return function (promise) { return promise.th ...

Client Blocking Issue: ExpressJS encountering problem loading JavaScript file

I recently deployed my express app on a server (specifically, I used Heroku). Everything functions perfectly when I test the app locally. However, when I access the app online, I encounter an issue with a net::ERR_BLOCKED_BY_CLIENT error. This error states ...

Retrieving information from PHP using AJAX

As a newcomer to the world of AJAX, I am faced with the task of retrieving data from a PHP file and storing it in a JavaScript variable. Despite exploring several examples, I have not been able to find a satisfactory solution. Here is a simplified HTML cod ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

Can AJAX pass arrays to HTML and then on to PHP?

I am facing a situation where I need to handle an AJAX call that returns an array to a PHP-HTML page. Below are snippets of code that depict the scenario: Javascript: "Please note that 'get_data.php' returns an HTML string, which I aim to stor ...

I'm having trouble getting NextJS dynamic routes to function properly on my local server

src/app/user/[username].js [username].js content: import { useRouter } from 'next/router' export default function User() { const router = useRouter() return ( <p> {router.query.username} </p> ); } Upon visiting ...

The header row in HTML tables sometimes vanishes unexpectedly after sorting the table

Upon filtering the table, I noticed that the header disappears sporadically. The issue is that the table header row should remain in place regardless of whether or not the characters used for filtering are present in the table rows. In Example 1: When fil ...

Troubleshooting Problems with jQuery's .remove() Function

I attempted to create a simple game using JS and jQuery, keeping in mind that I am new to both languages. My goal was to create a function that allows users to delete their save within the game. However, despite my efforts, I faced issues with the function ...

JQuery not being recognized by MVC4 view

I encountered an issue with my @Html.DropDownList that is supposed to invoke a jquery function, but it seems that the function is not being called. I've attempted the following: $(document).ready(function () { $('.test').change(function ...

Delay execution of Selenium WebDriver until the element appears on the screen

After scouring Google and the SO site, I was able to find answers for JAVA but not for node.js. I have a web application that has a slow loading time. I want the selenium program to wait until the page is fully loaded before taking any actions. Below is ...

Perform batch updates on multiple documents using MongoDB

How can I efficiently update multiple documents in MongoDB by iterating through an array of objects and then returning the modified documents in the response? Be sure to refer to the code comments for guidance .put(function (req, res) { var data = r ...

Async AJAX request and asynchronous C# controller function

Consider the following situation. I have an ajax request call in my ExtJS application. By default, the ajax call is set to asynchronous (async: true). On the server side, I also have a method that returns a Task, indicating it is also asynchronous. What i ...

Identifying the user's location within the application and dynamically loading various Angular scripts

Currently, I am working on a large-scale web application using Laravel and Angular. In this project, I have integrated various angular modules that come with their own controllers, directives, and views. One challenge I am facing is the need to load diffe ...

What is the best way to implement a unique function in an angularjs directive?

Is it possible to execute a custom function when clicking on the checkbox of a table row shown below? I am using the Angular Smart Table directive and need to be able to store the rowid or another property of the rows when the checkbox is clicked. app.dir ...

The unresponsive sticky navigation bar on a Joomla website is causing issues

I recently launched a new website that can be found here. The site includes the following JavaScript code: $(document).ready(function(){ $(window).bind('scroll', function() { var navHeight = $( window ).height() - 70; ...

Click the 'expand' button for additional details on every row in the table

I am facing a challenge with my HTML table where I have a lot of information to add for each row. However, displaying everything at once makes the page look cluttered. Therefore, I am looking to add a "view more" button in another column for each row. Des ...

Having trouble with the scrollbar appearance after updating Chrome?

I've encountered an issue with my code after the latest Chrome update. Is there a way to implement cross-browser styling for scrollbars? // Looking for Scrollbar Styling Solution const scrollbarStyle = { scrollbarColor: `${themeLayers.scrollBar[0 ...

Is it possible to initiate an animation in a child component using an input variable?

I have a specific animation that I would like to trigger once an *ngFor loop completes ngAfterViewInit(): void { this.items.changes.subscribe(() =>{ Promise.resolve().then(() => { this.everythingLoaded(); }) }) } After the loop fini ...

"Attempting to access $scope within the $http call results in an

Exploring my Angular code angular.module('MyApp'). controller('ProductController', function ($scope, DropDownService) { $scope.Product = {}; $scope.ProductCategoryList = null; DropDownService.GetCategory().then(function ( ...

Error encountered while attempting to display a view when pressing TouchableOpacity in a React Native application

Having trouble rendering a view when pressing on a TouchableOpacity in my React Native app. Any suggestions for a solution? import React, { Component } from 'react'; import { AppRegistry, View, TouchableOpacity } from 'react-nati ...