ts await foreach loop
Certainly! Here is a response:
async function processArray(array) {
for (const item of array) {
await delayedLog(item);
}
}
function delayedLog(item) {
return new Promise(resolve => setTimeout(() => {
console.log(item);
resolve();
}, 1000));
}
const myArray = [1, 2, 3, 4, 5];
processArray(myArray);
Explanation:
- Define an async function called processArray that takes an array as a parameter.
- Use a for...of loop to iterate through each item in the array.
- Use the await keyword to pause the execution of the async function until the delayedLog function is resolved for the current item.
- Define a delayedLog function that takes an item as a parameter and returns a Promise.
- Within the delayedLog function, create a Promise that resolves after a 1000ms timeout, during which it logs the item to the console.
- Create an array called myArray with some sample values.
- Call the processArray function with myArray as an argument to start processing the array items with a delay.