You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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的情况
);
关键说明
  1. async (item) => {}让每个map的回调返回Promise,Promise.all会等待所有Promise都resolve后,返回完整的带分类数据的数组。
  2. 用await替代then,代码更简洁,也能确保拿到分类结果后再返回对象。
  3. 如果这段代码是在Svelte Store的action中,直接把action定义成async函数即可,Svelte Store支持异步action。

内容的提问来源于stack exchange,提问作者Abdel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 06:54:23