Am I using async/await correctly in this code?

Here is the code snippet I am currently working with:

        var process = async (items: DCXComposite[], session: Session) => {
            // This function returns a response object with a statusCode property. If the status Code is 200, it indicates a successful operation.
            return await session.performBatchOperation();
        };

        try {
            var items: Composite[] = [];
            for (const project of projects) {
                items.push(project.getComposite());

                if (items.length === 50) {
                    var result = process(items);
                    items = [];
                }
            }
        } catch (err) {
            Logger.error('Failed to delete projects in batch', { error: err });
        }

I'm curious about how async/await works in this context. If one of the operations fails, does the entire process fail and trigger the catch block? In that case, would the next set of 50 projects not be processed? What happens if an error is thrown during the await phase?

The aim here is to efficiently delete multiple projects in batches through API calls. Each batch consists of sending a list of 50 projects to be deleted. Upon success, the process should return an object with a statusCode of 200.

Answer №1

If you prefer to handle your tasks in a sequential manner, pausing at the first error encountered, then following Unmitigated's advice, simply use the await keyword before calling your execute function (await execute(assets);).

If you're interested in running all tasks simultaneously and checking for any failures among them, you can store the Promises returned by each task and await their completion as a group:

const allResults = [];

try {
  for (const task of tasks) {
    // ...
    allResults.push(execute(/* ... */));
  }
  // Wait for ALL promises to finish, or catch an error on the first one
  await Promise.all(allResults);
} catch (error) {
  // ...
}

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

Trouble with exporting and importing an Express application

Starting with a simple Express example of 'Hello World', I am looking to refactor the code into separate files for configuration and routing. var express = require('express'); var app = express(); app.get('/', function (req, ...

Combining TypeScript into HTML resulted in an error: Uncaught ReferenceError clickbutton is not defined

Attempting to create a basic CRUD frontend without the use of any frameworks. I am encountering an issue when trying to include a TypeScript file (index.ts) in my index.html, as the functions called within it are showing as undefined. I understand that bro ...

Adjust the badge's color based on the status retrieved from the jQuery AJAX call

I've been working on retrieving data from an endpoint through a get request, and I'm looking to adjust the color of the request status based on the response. $.ajax({ type: 'GET', url: 'api/v1/service/tax', succe ...

Retrieving JSON information using Ajax to enhance Cytoscape visualization

Looking to share a network using Cytoscape web or, if possible, cytoscape.js. Due to the size of my data, I find it easier to export it from Cytoscape desktop and grab it using ajax in my HTML. Previously, before version 3.1.0 of Cytoscape, I could export ...

Transfer files with Ajax without the need for a form tag or submission

I'm trying to send images via AJAX without submitting a form. Normally, when submitting a form I can access the images using $_FILES['images']['tmp_name']; However, when trying to send files, I receive an object FileList in an arra ...

How to Incorporate Routes as Subroutes in Express.js

I am currently working on constructing a modular express.js server with a well-organized structure. I have experimented with using routes similar to components in React. index.js var syncsingle = require('./XYZ/syncsingle'); app.get('/sync ...

Learn how to showcase the current date by utilizing JavaScript arrays and the getDate method!

I have been struggling to format the date as follows: "Today is Sunday, the 31st day of March in the year 2019." I am working with JavaScript in an HTML5 document. Below is the code I have so far, and I would appreciate any help. I prefer not to rely on ...

What is the method for displaying an array separately for each item in JSON using JavaScript?

The issue arises when using for (let pet of person.pets) loop. In my JSON data, the "pets" field is an array but instead of getting a single array for each object, I am getting all pet arrays for every object in the JSON file. The desired outcome is to h ...

Reload a jquery pop up upon closing a pop up window

I have a modal pop up that appears after clicking an ASP button : <div class="form-group"> <asp:Button ID="btnBrand" runat="server" Text="Add brand" CssClass="btn btn-info" OnClick="btnAdd_Click" /> </div> Code Behind : protected ...

Exploring Firebase's Collection Retrieval through Vue.js

Trying to retrieve a specific collection from Firebase Firestore is giving me an error that I haven't been able to resolve yet. Below is the code snippet from my boot file: import { initializeApp } from "firebase/app"; import { getFirestore ...

From jQuery to Vanilla JavaScript: Implementing a simple click event listener

I've been attempting to translate the following jQuery code into vanilla JavaScript, however, I can't get it to function properly. jQuery: $(document).ready(function() { $("button").click(function() { var char = "0123456789abcdefghijklmno ...

Utilizing the Public Directory in Vite Compilation

One issue I encountered in my project with Vite version 2.9.7 is related to the handling of images stored in the public folder within the project's root directory. To import these images, I utilized Vite's import.meta.glob function, like so: imp ...

Progress bar indicating the loading status of an AJAX script

I am facing a challenge with creating a progress bar in AJAX. The entire page is loaded through AJAX, and one of the webpage elements uses AJAX to fetch large rows from the database. I have attempted to implement a progress bar within this script using a ...

Discover which npm module includes the lodash dependency

I've encountered a peculiar situation while using webpack to create a production bundle for my application. Even though I haven't explicitly installed `lodash` and it's not listed in my package.json file, I noticed that it's being added ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

The function of slidetoggle is malfunctioning when clicked

I currently have two dynamic containers with one displaying grouped boxes, quantities, and totals, while the other shows detailed information. Both container values are added dynamically at runtime. By default, the grouping container is displayed on the p ...

What is the best way to connect a Jquery plugin to a table within a partial view following an ajax request?

I have a main view that utilizes a partial view to display items in a table format. Main View (Enclosed within a div, it references the Partial View) <div id="divList"> @Html.Action("_list") </div> Partial View (Displaying a list of it ...

Embedding an image by inserting the URL

I have been attempting to implement functionality in Typescript where an image preview appears after a user enters a URL, but I have only been successful in achieving this in JavaScript. My goal is to display a preview of the image and enable the user to u ...

Attempting to set up an Ajax webform with various outputs, but encountering issues with functionality

I'm encountering an issue while creating interactive exercises. I want to display correct or incorrect answers immediately after submission using JSON for retrieving responses, as suggested in a forum. However, my AJAX code isn't working at all. ...

Using React to showcase a base64 image representation

I'm struggling to show an image that has been sent from my Node/Express server to my React application. I've tried looking at solutions on other platforms, but so far nothing has worked for me. Let me outline the steps I have taken: The image is ...