如何在Svelte Store的map函数中为.then内的变量赋值?
问题分析
你这段代码的核心问题是map是同步执行的,而getProductCategory返回的是Promise,then里的赋值是异步回调——当你return { ...item, category }的时候,Promise还没完成,category还是初始的空字符串。虽然之后then里能成功赋值,但这时候已经把带空category的对象返回了,无法再更新。
解决方案
把每个item的处理改成异步函数,用Promise.all等待所有分类请求完成后,再统一赋值:
// 确保这段代码在async函数内部执行 data.products.data = await Promise.all( data?.products?.data?.map(async (item) => { // 直接await获取分类结果,替代then回调 const category = await customPIMListStore.getProductCategory(item.productCategoryId, token); return { ...item, category }; }) || [] // 处理原数组为空/undefined的情况 );
关键说明
async (item) => {}让每个map的回调返回Promise,Promise.all会等待所有Promise都resolve后,返回完整的带分类数据的数组。- 用
await替代then,代码更简洁,也能确保拿到分类结果后再返回对象。 - 如果这段代码是在Svelte Store的action中,直接把action定义成async函数即可,Svelte Store支持异步action。
内容的提问来源于stack exchange,提问作者Abdel
相关产品推荐
相关产品推荐

