异步加递归问题,await被跳过?-灵析社区

Yourselffff

![](https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20241125/2f8e8a57b60997767f9ca12c6c40e9b0.png)函数recursive 是异步加递归 理想状态是:在函数updateParams调用 await函数recursive执行完后再执行后面代码。 实际:函数recursive还没执行完后面的代码就执行了 * * * async updateParams(type, keyword) { if(this.treeData.length === 0) { await this.recursive(this.vNode.childNodes) console.log("🐇 updateParams this.recursive👻", this.treeData) } console.log('查找-'); const data = this.treeData.find(item => item.path === type) this.setParams(data) const query = Object.assign({}, this.params,{ current : 1, size : 10000, data : keyword }) const res = await fetchPage(query) this.ids = res.data.data.records.map(i => i.id) }, * * * async recursive(data) { try { for (let i = 0; i { if(!item.isLeaf) { const Arr = [item] this.recursive(Arr) } this.treeData.push(item) }); } } } catch (error) { console.log('获取树形数据失败',error); } console.log('数据收集完毕'); }, * * * getQueryParams(res) { const data = res.data ? res.data : res return { id: data.id, filter: data.filter || '', path: data.path || '', fondsCode: this.current_fonds } },

阅读量:15

点赞量:0

问AI
"recursive" 方法内部实现的问题,Array 的 forEach 循环是不支持 async/await 的,所以应该把 forEach 部分换成 for 循环再配合 await ,如下: async recursive(data) { try { for (let i = 0; i < data.length; i++) { const item = data[i] if(item.isLeaf) {// 没有下级 const data = item.data ? item.data : item this.treeData.push(data) }else { const { data } = await fetchArchiveTree(this.getQueryParams(item)) for (let item of data.data) { if(!item.isLeaf) { const Arr = [item] await this.recursive(Arr) } this.treeData.push(item) } } } } catch (error) { console.log('获取树形数据失败',error); } console.log('数据收集完毕'); },