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

如何从Fetch请求中仅获取数据?Svelte Store遇Promise问题

Svelte Store 异步获取API数据返回Promise无法直接使用的解决方法

问题描述

在Svelte中开发Store时,尝试通过Fetch请求获取API数据,但在函数外部得到的始终是Promise对象,无法直接使用实际的Store数据。

原错误代码

import {writable} from "svelte/store";

const getPokedex = async function () {
    let pokedexData
    await fetch('https://pokeapi.co/api/v2/pokemon?limit=100&offset=0')
        .then(response => response.json())
        .then(data => {
            pokedexData = createPokedex(data)
        })
    return pokedexData
}

const createPokedex = function (data) {
    let pokedex = writable(data)
    // 其他逻辑...
}

export const pokedex = getPokedex();

问题原因

getPokedex是异步函数,调用它会直接返回一个Promise对象,而非createPokedex创建的writable Store实例。直接导出这个Promise,外部无法直接使用Store的响应式功能。

修正后的代码

import {writable} from "svelte/store";

const getPokedex = async () => {
    const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=100&offset=0');
    const data = await response.json();
    let pokedex = data.results
    return createPokedex(pokedex);
}

const createPokedex = function (data) {
    let pokedex = writable(data)
    // 其他逻辑...
}

export const pokedexStore = await getPokedex();

关键修复点

  1. 通过await获取异步结果:导出时使用await getPokedex()等待异步操作完成,拿到实际的Store实例而非Promise对象。
  2. 简化异步代码逻辑:用await替代.then链式调用,避免嵌套回调,让代码结构更清晰直观。

内容的提问来源于stack exchange,提问作者Alexis Van San

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:35:23