> For the complete documentation index, see [llms.txt](https://easonwang.gitbook.io/web_advance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://easonwang.gitbook.io/web_advance/js-ji-ben/javascript-hui-quan-yu-yi-bu-chu-li.md).

# JavaScript 迴圈與異步處理

## forEach

> 嚴格來說不算是回圈，因為無法使用 continue or break
>
> forEach 中 continue 對應為 return
>
> break 對應為 throw Error(...)

&#x20;foreach 內有 await，每個 foreach 不互相等待，但作用域內上一行有 await 會等待才執行下一行，等於多個 item parallel 執行。

例如：

```javascript
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function processItems(items) {
  items.forEach((item, idx) => {
      await sleep(1000);  // Simulate some delay
      console.log('Processed item:', idx);
  });
}

// Example usage
const items = [10, 20, 30, 40, 50];
processItems(items);
```

## for of

每個 iteration 對象互相等待 for of 有五個元素，會等到上一個元素的所有 await and promise 都執行完才繼續下一輪。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://easonwang.gitbook.io/web_advance/js-ji-ben/javascript-hui-quan-yu-yi-bu-chu-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
