Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to run functions iteratively with async await in JavaScript?
Running functions iteratively with async/await allows you to execute asynchronous operations in sequence within loops. This is useful when you need to process items one by one rather than concurrently.
Basic Syntax
async function iterativeFunction() {
for (let i = 0; i
Example: Sequential Function Calls
async function test(i) {
while (i
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Example: Processing Array Items
async function processItems(items) {
for (const item of items) {
await processItem(item);
}
console.log("All items processed");
}
async function processItem(item) {
// Simulate async operation with setTimeout
return new Promise(resolve => {
setTimeout(() => {
console.log(`Processed: ${item}`);
resolve();
}, 100);
});
}
const items = ['apple', 'banana', 'cherry'];
processItems(items);
Processed: apple
Processed: banana
Processed: cherry
All items processed
Key Points
Using await in loops ensures sequential execution. Each iteration waits for the previous async operation to complete before continuing. This is different from concurrent execution where all operations start simultaneously.
Comparison: Sequential vs Concurrent
| Approach | Execution | Use Case |
|---|---|---|
| Sequential (await in loop) | One by one | Order matters, rate limiting |
| Concurrent (Promise.all) | All at once | Independent operations, faster |
Conclusion
Use async/await in loops for sequential processing when order matters or you need to avoid overwhelming resources. This pattern ensures each operation completes before the next one begins.
Advertisements
