jbowden97
jbowden97

Reputation: 1

Async/await with multiple for loops

I am having a hard time wrapping my head around how aysnc/await works for my specific scenario. I have some for loops that I want to run parallel of each other but I also have other for loops that are dependent on the data create from one of the parallel for loops.

Loop 1 {
/* Delete some rows from a SQL Table */
}

Loop 2 {
/* Delete some rows from a SQL Table */
}

Loop 3 {
/* Add some rows to a SQL Table */
}

Loop 4 {
/* Update some rows from a SQL Table */
}

What I want to happen is Loop 1, Loop 2, and Loop 3 run in parallel instead of sequentially. I don't want Loop 4 to run until Loop 3 has finished. How could this be achieved with async/await. I am trying to improve runtime of this code but I need to use for loops to iterate through data in the database.

Alternatively, if there is a way to reduce the time complexity using a different method instead of for loops I am open to suggestions.

Upvotes: 0

Views: 971

Answers (1)

sitcomguy
sitcomguy

Reputation: 121

await Promise.all(promiseLoop1, promiseLoop2, promiseLoop3);

await promiseLoop4;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Edit:

In addition, you can build the SQL command string using loops but only call SQL once.

You may also want to look into SQL Transactions:

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/transactions-transact-sql?view=sql-server-ver15

Upvotes: 1

Related Questions