## 問題描述
eg: 在數據量比較小,后臺只提供了根據樹 `父節點` 請求 `子節點` 的數據,此時就需要通過 `遍歷` 的方式同步將數據處理為樹狀結構。但是我們會遇到遍歷時無法按序獲取數據的問題,像下面的例子
~~~
// http api
const getNodeByParentId = async (id) => {
// 模擬異步的一個方法,方便直觀顯示
// 隨機生成 100 ~ 500 ms 的延遲
const time = Math.floor(Math.random() * 400) + 100;
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
resolve(id);
}, time);
} catch (err) {
reject(err);
}
})
}
~~~
1. 定義一個數組
~~~
const treeData = [1, 3, 5];
~~~
2. 遍歷數組,調用異步方法數組數組內容,發現每次返回的數據順序可能都不一樣
~~~
treeData.forEach(async item => {
console.log(await getNodeByParentId(item));
})
~~~
## 解決方案
1. 自調用式方法 for 循環
~~~
console.log(1);
await (async function () {
for (let i = 0; i < treeData.length; i++) {
const res = await getNodeByParentId(treeData[i]);
console.log(res);
}
})()
console.log(2);
~~~
2. for of (推薦)
~~~
console.log(1);
for (const item of treeData) {
const res = await getNodeByParentId(item);
console.log(res);
}
console.log(2);
~~~
3. map
> map 結合 promis可以實現異步等待; 但是 map 內部函數的執行順序不是按照預期執行的,所以適合于不在內部處理一些邏輯
~~~
console.log(1);
await Promise.all(treeData.map(async id => console.log(await getNodeByParentId(id))));
console.log(2);
~~~