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

SvelteKit流式Promise返回不稳定:有时为空数组有时有数据

问题分析与修复方案

核心问题1:后端数据查询逻辑错误

你的db.ts中getByRequestId方法接收了id参数,但完全没有使用它进行数据过滤——当前代码会返回mediaItemComments集合的全部数据,这不仅不符合接口设计意图,也可能是前端数据不稳定的潜在诱因(比如集合数据变化时前端拿到的内容不可控)。

修复代码:

export const mediaItemComment = {
    getByRequestId: async(id: string) => {
        // 添加where条件,过滤对应requestId的评论(假设关联字段为requestId,可根据实际表结构调整)
        const ref = await db
          .collection('mediaItemComments')
          .where('requestId', '==', id)
          .get()

        const comments = ref.docs.map((doc) => ({ id: doc.id, ...doc.data() }))
        console.log('DB.TS ran and fetched these comments: ', comments.length)
        return comments;
   }
}

核心问题2:前端Promise处理时机不当

你在MediaItemModal的onMount中处理streamedComments,但onMount的执行时机不一定和streamed Promise的就绪时机匹配——如果Promise还未完成,await可能拿到空值;或者组件传递过程中Promise被意外处理。

推荐两种更可靠的处理方式:

方式1:使用Svelte模板{#await}语法(最稳妥)

直接在模板中处理Promise的状态,无需手动在script中赋值:

<script>
    export let streamedComments;
</script>

{#await streamedComments}
    <div>加载评论中...</div>
{:then loadedComments}
    {#each loadedComments as comment}
        <div class="comment-item">
            <p>{comment.content}</p>
            <!-- 渲染其他评论字段 -->
        </div>
    {/each}
{:catch error}
    <div class="error">加载评论失败:{error.message}</div>
{/await}

方式2:顶层直接await替代onMount

如果需要在script中处理数据,可直接在顶层执行await,无需依赖onMount:

<script>
    export let streamedComments;
    let comments = [];

    // 顶层异步函数处理
    (async () => {
        try {
            comments = await streamedComments;
        } catch (error) {
            console.error('Failed to load comments:', error);
        }
    })();
</script>

<!-- 渲染comments数组 -->
{#each comments as comment}
    <div class="comment-item">{comment.content}</div>
{/each}

额外检查项

  • 检查Art、SpecialCarousel组件中streamedComments的prop传递是否正确,避免拼写错误或中途修改Promise对象(比如不小心提前await了)。
  • 若前端仍出现偶发空数组,可在MediaItemModal的script中打印streamedComments的状态,确认传递的是原始Promise而非已解析的空值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 12:15:10