Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything functions as expected, but I am looking for a way to allow the loop to continue execution after handling errors. At present, when an error is caught, it gets logged into the database, but the loop halts and no further calls are executed. I have attempted using "return" and "continue" inside the catch block without success.

Below is an example of the code:

// This is a section of a larger loop. Needs to be asynchronous
await paymentInfo.forEach(async ln => {

        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        var finalPayment = await service.createPayment(args)
          .then(console.log("Payment created"))
          .catch((err) => { 

            // Log the error to the database
            service.dbUpdate(err)
            .then(console.log("Error Logged to DB"))
            .catch(() => {})

            // How do we proceed from here?
       })
      // Update the database with payment ID here
})

In essence, I simply want to be able to continue to the next iteration of the loop after catching an error. As far as I can see, there isn't a straightforward way to achieve this. Any suggestions would be greatly appreciated.

Answer №1

If you are already using async/await, there is no need for .then method. Simply utilize await and catch errors with a traditional try/catch block. The continue statement will work naturally when placed inside a for loop. However, it appears that you need to handle the loop iterations in parallel, so each iteration should be contained within a function invocation where you can return.

Another issue present is the lack of error handling in your async function due to not being awaited. Instead of awaiting forEach, which does not return anything, one solution is to map your array into an array of promises (the result of executing anonymous async functions) and then await all those promises simultaneously using Promise.all.

await Promise.all(paymentInfo.map(ln => (async () => {
        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        try {
            var finalPayment = await service.createPayment(args)
            console.log("Payment created")
        } catch (err) {
            // Log error to DB
            try {
                await service.dbUpdate(err)
                console.log("Error Logged to DB"))
            } catch (e) {}

           return
        }

       // Database update here with payment ID
})())

It may be unnecessary to have a continue statement if the only purpose was to react to the possibility of a payment not being created. In such case, you would simply use the payment value unconditionally, as any error thrown would skip the rest of the try block anyway!

await Promise.all(paymentInfo.map((async ln => {
        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        try {
            var finalPayment = await service.createPayment(args)
            console.log("Payment created")

            // Database update here with payment ID
        } catch (err) {
            // Log error to DB
            try {
                await service.dbUpdate(err)
                console.log("Error Logged to DB"))
            } catch (e) {}
        }
})())

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

Resposiveness of force-directed graph is lost

const container = document.getElementById("container"); const svgElement = d3.select(container).append("svg") // Get the width and height computed by CSS. let width = container.clientWidth; let height = container.clientHeight; const colorScale = d3.scale ...

Obtaining varied outcomes while printing filtered information

As a beginner in React.js using hooks, I prefer to learn through hands-on coding. My query revolves around fetching data from a specific URL like ksngfr.com/something.txt and displaying it as shown in the provided image (I only displayed numbers 1-4, but t ...

An error has occurred with TokBox: OT.Session is unable to connect because the session has already been declared as

I encountered a similar issue but I'm struggling to make sense of what's going on. I have created a .Net page that includes all the necessary TokBox methods for subscribing. The process involves launching a new window (video monitor for multiple ...

Is Node.js functioning properly, but how can I incorporate it into a web browser?

I have a SQL Server table that I want to display in a web browser using the DataTables jQuery plugin. The code below works well for outputting data in the command line, but I need it to be displayed in the browser, possibly in JSON format. I am utilizing ...

Deconstructing arrays in the req.body object in a Node.js Express application

Received an array in the request body as follows: [ { "month" : "JUL", "year" :"2018" }, { "month" : "JAN", "year" :"2018" }, { "month" : "MAR", "year" :"2018" } ] This array consists of two parameters (month:enum and year:string). ...

Tips for developing an asynchronous function for data requests in reactjs

I need assistance with retrieving data from the dataAllMovies.js file using an asynchronous function. The current approach I tried is not working as expected. dataAllMovies.js const id = Date.now(); export const dataAllMovies = { movies: [ { ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Question about using React, NPM, Vite, Babel, and Node.js together

I want to confirm my understanding. So, if I decide to create a react 'app' and incorporate babel for jsx support. Then, I opt for vite for enhanced development runtime and packaging. Lastly, I utilize node.js to execute my code. To sum it up, ...

What triggers the execution of the catch method while chaining HTTP promises?

In my Angular application, I have developed a custom loaderService that displays a loading spinner while the back-end processes requests. Below is the code snippet: export class ComponentOne { constructor(loaderService: LoaderService, orderService: Orde ...

Unable to display an image element in fullscreen within a modal that is already fullscreen

I am facing an issue with my modal that is designed to occupy the full width and height of a browser. Inside this modal, there is an image enclosed within a div along with some other elements. My goal is to make the image go full screen in the browser, aki ...

Trouble updating outside controller data while using AngularJS directive inside ng-repeat loop

I am currently working with a isolate scope directive that is being used inside an ng-repeat loop. The loop iterates over an array from the controller of the template provided below: <!DOCTYPE html> <html> <head> <link rel="sty ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

Adjusting the size and location of the current browser window using jQuery

Is there a way to modify the height, width, and position of the browser window using jQuery's document.ready() function? ...

Problems with Key Presses in Form Verification

Yesterday evening, our supervisor called me to report an issue with our app. He mentioned that when he tried to log in using a dummy password, the validation was successful. It seems that clicking on the mouse to authenticate the password was working corr ...

"Learn how to use jQuery to retrieve a specific row from an HTML table based on equality with a certain

I have a dynamically generated table using PHP. The information in this table is related to different semesters (such as first, second, third, etc.). I want to display specific semester information when a user clicks a link from the same table without need ...

Tips for inserting HTML into elements using Angular

Recently, I delved into Angular and decided to experiment with Ajax by fetching a document to display on my webpage. The process worked flawlessly, but now I face a new challenge: injecting HTML content into a DOM element dynamically. Typically, this task ...

Ensuring input validity and blocking changes if not compliant with AngularJS patterns

I am looking to create an input field that only accepts the values 1, 2, or 3. To achieve this, I am working on a directive that will prevent any changes to the model if it doesn't match these specific values. For example, if the value is 1 and I tr ...

Tips for transferring data from Express to .ejs file during redirection in Node.js

When I submit the login form in my login.ejs file, the page redirects if the details are correct. If the password is wrong, however, I want to display a message in the .ejs file indicating this. Below are the details: Here is the code in my app.js file - ...

Executing HTTP Requests for Elements in an Array using JavaScript

I am currently struggling with a script that sends HTTP requests to a website in order to obtain various documents. The document IDs are stored within an array, and my intention is to send a request for each element in the array and return a unique message ...

AngularJS - Sending event to a specific controller

I am facing an issue with my page where a list of Leads each have specific actions that are represented by forms. These forms can be displayed multiple times on the same page. Each form has its own scope and controller instance. After submitting a form, an ...