[英]How to use promises with recursive fetch?
我正在使用訪存來一次檢索一棵樹。 獲取所有分支后,如何觸發動作? 這棵樹有多個分支,我事先不知道深度。
偽代碼:
until Children is empty fetchChildren()
after all children are retrieved doSomething()
我找到了一些答案,但是它們只處理鏈式then(),而不處理樹。
[edit]盡管不是強制性的,但我希望該解決方案可以在IE11中運行。 我已經在使用promise並獲取polyfill。
只需首先等待獲取圖層元素,然后遞歸地繼續處理子元素,然后等待:
async function fetchChildren(layer) {
await Promise.all(layer.map(fetch));
await Promise.all(layer.map(el => fetchChildren(el.children)));
}
( fetch(el)必須是一個有前途的函數 )
這是一種使用遞歸異步函數來完成此操作的方法,該函數在返回諾言之前等待元素的子代的提取完成。
這樣,當一切完成后,我們可以調用doSomething
。
const tree = { url: 'http://www.json-generator.com/api/json/get/cevhxOsZnS', children: [{ url: 'http://www.json-generator.com/api/json/get/cguaPsRxAi' }, { url: 'http://www.json-generator.com/api/json/get/cguaPsRxAi', children: [{ url: 'http://www.json-generator.com/api/json/get/cfDZdmxnDm' }] }] }; function doSomething() { console.log("doing something"); } async function fetchIt(element) { if (element.children) { await Promise.all(element.children.map(fetchIt)); } return new Promise((resolve) => { console.log("fetching " + element.url); fetch(element.url).then(res => { console.log("done"); resolve(); }); }); } fetchIt(tree).then(doSomething);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.