请问如何优化这个存在异步逻辑的滚动事件监听函数?-灵析社区

复古直男

async _handleBrandListScroll() { const { ids, mainScrollerOffset } = this.data; let indexs: number[] = []; for (const id of ids) { const [[{ top: rectTop }]] = await queryBoundingClient(this, id); if (typeof rectTop !== 'number') continue; if (rectTop <= mainScrollerOffset) { const idIndexs = getIdIndexs(id); if (!_.isUndefined(idIndexs)) { indexs = idIndexs; } } else { break; } } const [mainIndex, subIndex] = indexs; if (this.data.currentLeftTabIndex !== mainIndex) { this.setData({ currentLeftTabIndex: mainIndex }); this.updateCurrentTopTabList(mainIndex); } if (this.data.currentTopTabIndex !== subIndex) { this.setData({ currentTopTabIndex: subIndex }); this.updateTopTabsScrollLeft(subIndex); } }, 主要问题是 queryBoundingClient 是异步返回结果的(在微信小程序环境中),导致 _handleBrandListScroll 的 throttle 无效,结果 indexs 不准。体现在视图上就是,滑动过快时当前选中的 tab 来回横跳。

阅读量:278

点赞量:5

问AI
async _handleBrandListScroll() { const { ids, mainScrollerOffset } = this.data; let indexs: number[] = []; // Step 1: 批量处理异步请求 const rectTops = await Promise.all(ids.map(id => queryBoundingClient(this, id))); for (let i = 0; i < rectTops.length; i++) { const [[{ top: rectTop }]] = rectTops[i]; if (typeof rectTop !== 'number') continue; if (rectTop <= mainScrollerOffset) { const idIndexs = getIdIndexs(ids[i]); if (!_.isUndefined(idIndexs)) { indexs = idIndexs; } } else { break; } } const [mainIndex, subIndex] = indexs; if (this.data.currentLeftTabIndex !== mainIndex) { this.setData({ currentLeftTabIndex: mainIndex }); this.updateCurrentTopTabList(mainIndex); } if (this.data.currentTopTabIndex !== subIndex) { this.setData({ currentTopTabIndex: subIndex }); this.updateTopTabsScrollLeft(subIndex); } },