The step-by-step guide to implementing async/await specifically for a 'for loop'

Is there a way to make 'submitToTheOthers' function run after 'let items = []' has completed, without needing an await within 'submitToTheOthers'? I am considering using await within the for loop in 'submitToTheOthers', but I'm unsure how to do so.

If I were to use await within 'updateGeneralInfoToOther', it would mean that each server would not be updated simultaneously, and if any server encounters an error, the process would halt. Is there a better approach involving promises or another method to handle this situation?

Any suggestions on how to ensure that 'submitToTheOthers' waits before executing further actions?

PS) I am particularly interested in older syntaxes as I may need to support Internet Explorer XD XD TT

Settings.vue

<template>
  <div>
    <button class="point" @click="submitTotalServer()">submitTotalServer</button>
  </div>
</template>

... (omitted for brevity)

api/settings.js

// ...
export function updateGeneralInfoToOther(id, data, serverAddress) {
  axios.defaults.timeout = 5000;
  data.serverAddress = serverAddress
  
  return axios.post(`/api/settings/generalToOther/${id}`, data)
}
// ...

Answer №1

The main issue at hand is that the `for` loop in your code does not wait for the promise returned by `updateGeneralInfoToOther()` to complete. To fix this, you simply need to make sure the loop `awaits` the promise, like so:

for (let i=0; i<this.idxs.length ;i++) {
    await updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then((res) => {
        if (res.status == 200) {
            this.serverResCheck[i]= true
        } else {
            this.serverResCheck[i]= false
        }
    })
}

However, this approach has its drawbacks. You are awaiting each request separately, which can be improved. A better solution would be to execute all async operations simultaneously and then wait for them to finish together. The `submitToOthers()` function could return an array of promises instead:

return this.idx.map((_entry, i) => {
    return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then((res) => {
        if (res.status == 200) {
            this.serverResCheck[i] = true
        } else {
            this.serverResCheck[i] = false
        }
    })
});

Then, you can utilize Promise.all() to await the resolution of this promises array:

async submitTotalServer() {
    await Promise.all(this.submitToTheOthers());

    // Additional logic goes here
    // ...
}

Answer №2

perhaps this could be what you're looking for for await

 async function test() {
let numbers=[1,2,3,4,5]
          for await (const element of numbers) {
           
             console.log(element);
          }
       }

Answer №3

When you declare a function as async, you are instructing it to pause execution at any await keyword until the awaited promise is either resolved or rejected. In your submitToTheOthers function, however, there are no await calls, causing all requests to be sent simultaneously and the function to return without waiting for them to complete.

While adding an await before each call would address this issue, it would also result in sequential processing where each iteration waits for the previous one to finish. This approach might be slower compared to sending all requests concurrently, which appears feasible based on the provided code snippet.

To execute these requests in parallel, you can utilize Promise.all(), a method designed for handling multiple promises concurrently. The revised implementation below should achieve the desired outcome without requiring extensive modifications:

submitToTheOthers() {
  return Promise.all(
    this.idxs.map((_, i) => updateGeneralInfoToOther(
      1,
      { data: 'test' },
      this.serverFullAddress[i]
    ) 
      .then(r => { 
         this.serverResCheck[i] = r.status === 200;
         return r;
      })
      .catch(e => {
         this.serverResCheck[i] = false;
         return e;
      })
  ));
}

Answer №4

Despite labeling async submitToTheOthers, it does not actually function as an asynchronous function.

Within the function, the async line appears to be:

updateGeneralInfoToOther(1, data, this.serverFullAddress[i]')
. This function is called in a loop, but the issue arises from not using await or returning the promise.

To address this, you must include await before it, which will cause each iteration to wait for the previous one. Alternatively, you can store each promise in an array and use await Promise.all(promises) at the end of the function.

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

Using AngularJS, you can easily merge one array of data into another array

In my coding environment, I am working with two arrays. The first array is called `$scope.workingSchedules` and it contains data related to working hours for different days of the week. $scope.workingSchedules=[ { ...

Screening for items that meet specific criteria

Currently, the functions are functioning properly by filtering inventory based on barcode and manufacturer. However, I am looking to enhance it to behave like default angularjs filtering. Specifically, I want it so that if I select manufacturer - LG and ba ...

Utilize Reactjs to efficiently showcase a collection of arrays within an object

I am struggling with a JSON file that has nested dropdown mega menu levels and I can't figure out how to map and render multiple levels of arrays and objects to create a tree-like structure. Here is my current JSON Structure: { "megamenu": [ { ...

Unable to construct React/Next project - identified page lacking a React Component as default export (context api file)

When attempting to compile my Next.js project, I encountered an error message in the terminal: Error: Build optimization failed: found page without a React Component as default export in pages/components/context/Context The file in question is utilizing ...

Checking for the Existence of a Class Element within a String using JavaScript

Within my web project, there is a scenario where if a user has been logged out in one browser tab, they will automatically be redirected to the login page in any other browser tab after interacting with that page (such as clicking on a link). However, this ...

Storing the API key returned by the Node.js store as a variable was

Just starting out with node and experimenting with A node.js library for the Pardot API I provide my userKey, email, and password to pardot, which returns an api_key. This is the code snippet I am using for authentication. Upon running my node server, I ...

What a great method to execute a button click within the same button click using jQuery!

Here's an example of code that attempts to make an ajax call when a user clicks a button. If the ajax call fails, the button should be reclicked. I've tried this code below, but it doesn't seem to work. $("#click_me").click(function(){ ...

AngularJS array value with HTML tags is not displaying properly upon invocation

In Angular, I have an array that has the following structure: $scope.posts = [ { "ID" : id(), "Title" : "A", "Company" : "Company A", "Location" : "San Francisco, CA", "Date" : "2016-06-20", "Description ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

How can the Angular Js framework be utilized to create a pop-up feature in combination with Bootstrap?

I'm currently working on a website using AngularJS and Bootstrap. When the site is loading, I make a server call to fetch some data. This process takes some time, and during this interval, I want to display a pop-up message indicating that the user s ...

Adding a variable to the .append function in HTML code

I am currently working on a way to include the current date and time when a user comments on a post in my forum. While I have successfully managed to upload the text inputted by the user into the comment section, I am now looking to also dynamically insert ...

Encountering an Internal Server error with Mongoose in Node.js

My latest project is a web application designed for photo sharing. One particular route in the app is responsible for retrieving and displaying photos from all users in the following array. This is the route: router.get('/getphotos',function(r ...

Exploring the single slot functionality in components: A step-by-step guide

`I'm working on a component with multiple slots, namely: header slot, main slot, and footer slot base-layout.vue <template> <div class="container"> <header> <slot name="header"></slot> ...

Using Javascript to replace elements with input fields and text areas

I'm currently working on a unique project for my Wordpress blog, where I am developing a custom block editor using JavaScript on the frontend. The goal is to convert all elements from the post content into a series of inputs and textareas. To begin, ...

Is it feasible to design a distinctive layout while utilizing a v-for loop in Vue 2?

I am currently in the process of designing a questionnaire. Within my array, each question is represented as an object. As I iterate through them using <component :is>, this component property guides how the question will be displayed - for example, ...

Is it possible to alter the css twice through the action of clicking on two individual buttons

One feature I have in my interface allows users to click on the edit button to bring up borders and change the background color of other divs. Once the edit button is pressed, it is replaced by cancel and save buttons. The goal is for the borders and backg ...

Ongoing state configuration in a React hook

My custom hook: export function useToken2() { const { data: session, status } = useSession(); const [token, setToken] = useState<string | null>(null); useEffect(() => { if (status === 'authenticated' && session?.accessToken) { ...

Retrieve the name of the product from the corresponding parent element

My goal is to trigger an alert box with the product name when the "Buy now" button is clicked. I have added the necessary code in jquery to maintain the onclick event of the button. <h2 class="product-name"><a href="product1.php" title="Sample Pr ...

Utilize jQuery in phantom.js to send an ajax request across domains

I am currently in the process of testing a chrome plugin by emulating a portion of its functionality on phantomjs. My objective for phantom seems quite straightforward, yet I am encountering issues. I aim for it to navigate to a specific webpage and withi ...

Obtain an Element Using Puppeteer

Currently grappling with a sensitive issue concerning puppeteer. The HTML structure in question is as follows: <tbody> <tr rel="0" class="disabled" id="user6335934" class="odd"> ...