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

如何处理Fetch返回的Promise格式JSON值?Asp.Net Core请求问题

问题分析与解决方案

你的问题核心在于 response.json() 是异步操作,返回的是Promise对象,而非直接的JSON数据,但你在WebRequestResult构造函数里直接将其赋值给this.JSON,导致后续访问时拿到的是Promise而非解析后的JSON对象,自然无法通过属性获取值。

具体问题点

  1. WebRequestResult构造函数中,this.JSON = response.json() 保存的是Promise,不是解析后的JSON数据
  2. obj getter尝试用JSON.parse(this.JSON)解析Promise,这完全错误——Promise不是JSON字符串,解析后返回undefined

修复方案

步骤1:修改FetchAsync函数,先解析JSON再传入WebRequestResult

将异步解析JSON的逻辑提前到FetchAsync中,确保传递给WebRequestResult的是实际的JSON数据:

static FetchAsync = async (url, body = {}, method = "get", credentials = "same-origin", mode = "same-origin") => {
    const response = await fetch(url, {
        method: method,
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        credentials: credentials.toLowerCase(),
        mode: mode.toLowerCase(),
        body: body && Object.keys(body).length > 0 ? JSON.stringify(WebRequestUtility.ProcessBodyData(body)) : null
    });

    if (response.ok) {
        // 先等待JSON解析完成,再传入WebRequestResult
        const parsedJson = await response.json();
        return new WebRequestResult(response, parsedJson);
    } else {
        throw new Error(`Request failed: ${response.status}. Status: ${response.statusText}. URL: ${response.url}`);
    }
};

步骤2:修改WebRequestResult类,接收已解析的JSON数据

更新构造函数,直接存储解析后的JSON对象,同时简化obj getter:

class WebRequestResult {
    constructor(response, jsonData) {
        this.Response = response;
        this.Success = response.ok;
        this.Status = response.status;
        this.StatusText = response.statusText;
        this.Type = response.type;
        this.JSON = jsonData; // 现在是解析完成的JSON对象
    }

    get obj() {
        return this.JSON; // 直接返回已解析的对象,无需再次parse
    }
}

使用方式

现在调用FetchAsync时,只需await获取结果后,直接访问JSON或obj属性即可拿到实际数据:

async function loadData() {
    try {
        const result = await YourClassName.FetchAsync("/api/your-endpoint");
        // 直接访问JSON属性
        console.log(result.JSON.targetProperty);
        // 或者使用obj getter
        console.log(result.obj.targetProperty);
    } catch (error) {
        console.error("加载数据失败:", error);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:51:23