如何在所有图标文件加载完成后resolve Promise?解决nodes丢失问题
解决请求与nodes关联丢失的问题
你的问题核心是没有将每个fetch请求和对应的nodes绑定在一起,导致Promise.all完成后无法找到请求内容对应的节点集合。可以通过在每个Promise中保留nodes的引用,让每个请求的结果携带对应的nodes来解决。
修改后的完整代码如下:
function request(): Promise<void> { const promises: Promise<{ content: string; nodes: LayerNode[] }>[] = []; for (const [src, nodes] of this.icons.entries()) { // 每个Promise在获取内容后,将content和对应的nodes一起返回 const fetchPromise = fetch(`${this.baseHref}assets/images/${src}`) .then(res => res.text()) .then(content => ({ content, nodes })); promises.push(fetchPromise); } // 等待所有请求完成,遍历每个结果处理对应的nodes return Promise.all(promises).then(results => { results.forEach(({ content, nodes }) => { nodes.forEach(node => { const { icon } = node; const { color } = icon; const replaceIcon = getReplaceIcon(this.defPointIcon, color); const defIcon = getDefIcon(content, color); this.cachedIcons.set(node, { defIcon, replaceIcon }); }); }); }); }
关键改动说明:
- 绑定请求与nodes:在循环中创建Promise时,不再只返回fetch的结果,而是将请求到的
content和当前循环的nodes打包成对象返回,确保每个请求的结果都携带对应的节点集合。 - 统一处理所有结果:Promise.all返回的
results数组中,每个元素都包含了content和对应的nodes,遍历这个数组就能精准地将每个图标内容与它的节点关联处理。 - 返回顶层Promise:整个
request函数返回Promise.all的结果,外部调用方可以通过await request()或者request().then(...)来等待所有图标加载和处理完成。
内容的提问来源于stack exchange,提问作者Arvia
相关产品推荐
相关产品推荐

