[typescript] await for...of 문을 사용하는 예시 코드

for...of statement in TypeScript can be used to iterate over asynchronous iterable objects such as arrays, strings, or other iterables that return promises. You can combine await with for...of to iterate and wait for each promise to resolve.

Here’s an example of using the await for...of statement in TypeScript:

async function asyncFunction() {
  const iterable = [1, 2, 3, 4, 5];

  for await (const item of iterable) {
    const result = await someAsyncFunction(item); // Replace someAsyncFunction with your actual asynchronous operation
    console.log(result);
  }
}

async function someAsyncFunction(num: number): Promise<string> {
  return new Promise((resolve) => {
    setTimeout(() => resolve(`Processed ${num}`), 1000);
  });
}

asyncFunction();

In this example, the asyncFunction uses the for await...of statement to iterate over the iterable array. For each item in the iterable, it calls the someAsyncFunction to perform an asynchronous operation and waits for the result before moving to the next item.

You can use this pattern to handle asynchronous iterations in TypeScript.

For more information on for...of statement and asynchronous iteration in TypeScript, you can refer to the official TypeScript documentation: Iterables and Iterators