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

Spring application: Unable to find a handler for portlet request with mode 'view' and phase 'Resource_PHASE'

It seems like everything is set up correctly, but for some reason, my ajax call fails with the error message "No handler found for portlet request: mode 'view', phase 'Resource_PHASE'". The handler URL I'm using is "getAllFruit", ...

Is it true that document.execCommand only works with buttons and not links?

Below is the code snippet I am working with: <div contenteditable="true" style="height:100px;width:100px;border:1px solid; " class="editor"></div> <a class='bold' style="height:10px;width:10px;">B</a> $(function(){ ...

How can you modify the color of a card in React by mapping through an array and evaluating its value?

I'm attempting to modify the color of a card depending on the current slot value, which is an object in an array. While I am iterating through each card, I want to adjust the background color of the card based on this value. However, my current method ...

Utilize context.isPointInPath(x, y) in HTML5 Canvas for intricate shapes that contain multiple paths

I am currently working on a project that involves drawing a complex shape composed of 6 thin lines and two thick lines. In my code, I have defined 8 paths to achieve this: context.save(); context.lineWidth=2; var TAB_ABSTAND=10; var T ...

Incorporate axios within getStaticProps while utilizing Next.js

I am working on a new project where I am utilizing axios to handle request data. However, I am facing an issue when using axios in the getStaticProps function which results in an error on my index.js page. Here is a snippet of my index.js code: import ...

Display everything when an option is clicked

I have a filter that is working perfectly. When I select a specific category, it filters out only rows with that category. However, I am stuck on how to display all rows again after clicking on the first option. My objective is to show all rows when "Categ ...

Searching for different forms of multiple words using regular expressions

I have a value saved in a variable: var myvalue = "hello bye"; var myText = "hellobye is here and hello-bye here and hello.bye" Is there a way to check if different versions of myvalue are present in the text? I am currently using this pattern: hello ...

Having trouble with test coverage in Mocha using Blanket?

I have a Node application that I want to test and generate a coverage report for. I followed the steps outlined in the Getting Started Guide, but unfortunately, it doesn't seem to be working correctly. In my source code file named src/two.js: var tw ...

Does the notion of "Execution context and the stack" only pertain to web browsers?

Does the concept of "Execution context and the stack" only apply to browsers, or is it also utilized in other environments such as NodeJS? I've crafted 2 statements but unsure if they are accurate: 1- "The environment for JavaScript is not solely the ...

Calculate the combined sum and alter the values of three input fields

There are three text boxes (testbox, testbox2, testbox3) that receive values from an input field, radio button selection, and checkbox. The correct values are displayed in testbox, testbox2, testbox3. Additionally, the sum of testbox, testbox2, testbox3 n ...

Ways to display the modal once the user initiates the action

Is there a way to delay loading my modal HTML codes until after the user clicks a button, rather than having them load automatically with the template? HTML <!-- Template Codes--> <button data-toggle="modal" data-target="#modal-content" type="bu ...

Exploring the bounds of self-invocation functions in JavaScript

Have you ever wondered why self-invocation functions inside another function in JavaScript don't inherit the scope of the outer function? var prop = "global"; var hash = { prop: "hash prop", foo: function(){ console.log(this.prop); ...

JavaScript: set values to elements in an array

Below is the code snippet I am working with: function gotData(data){ result = data.val() const urls_kws = Object.keys(result) .filter(key => result[key].last_res > 10) var keywords = urls_kws; c ...

Finding a path match with Regexp using path-to-regexp

When obtaining a user's information by their unique id: /user/{id} I convert this path to a regular expression: pathToRegexp(path.replace(/\{/g, ':').replace(/\}/g, '')) Next, I compare it with: const matchedPaths = ...

What steps should I follow to incorporate channel logic into my WebSocket application, including setting up event bindings?

I'm currently tackling a major obstacle: my very own WebSocket server. The authentication and basic functionality are up and running smoothly, but I'm facing some challenges with the actual logic implementation. To address this, I've create ...

Setting global variable values when a button is clicked in Javascript

My query involves JavaScript. I have an HTML template with a button (b1) that, when clicked, assigns an array to a variable called tempdata. The issue arises when trying to display this tempdata array using alert() outside the onclick function; nothing hap ...

The Handsontable popup autocomplete editor is unfortunately truncated by the horizontal scrollbar

I have implemented an autocomplete feature on all columns in my project. However, I am facing an issue where the autocomplete editor gets cut off by the horizontal scrollbar. You can see the problem demonstrated in this jsfiddle link. Here is some code re ...

Implement a new list field to an object using javascript

I am facing a challenge in converting a JSON object to a list of JSON objects and then adding it back to JSON. Here is an example: config = { existing_value: 'sample' } addToListing = (field, value, index=0) => { config = { ...confi ...

Asynchronous waterfall call in Node.js to call the method before

Is it possible to invoke a previous method within async.waterfall from a subsequent method? async.waterfall([ function (callback) { }, function (reservationStatus, callback) { }, function (reservationStatusList, f ...

Contact form repair completed - Messages successfully delivered

I am facing an issue with the contact form on my HTML landing page. Currently, when you click the 'Submit' button, it redirects to a new PHP page displaying 'Success'. Is there a way to make it so that upon clicking 'Submit' a ...