首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否可以使用fetch返回JSON对象?

是否可以使用fetch返回JSON对象?
EN

Stack Overflow用户
提问于 2018-06-10 03:18:22
回答 1查看 670关注 0票数 0

三天以来,我一直在尝试使用fetch API来获取JSON对象,我搜索了几乎所有我能找到的线程。所以我有一个使用fetch的函数,我希望这个函数返回一个JSON对象,但当我试图打印它时,它是一个Promise对象。我发现fetch实际上是在返回Promise对象。那么,如果fetch不可能返回JSON对象,我如何从Promise对象获取JSON对象呢?_ParseJSON中的console.info正确地打印出我想要的JSONObject,但是在fetch之外,不可能重新构造JSON。

代码语言:javascript
复制
import React from 'react';

export class JSONObject {
constructor(_url) {
    this.URL = _url;
    this.importedJSON = null;

    this.state = {}; //Init getter setter
}

ParseCurrentUrl() {
    this.importedJSON = this._ParseJSON();
    console.info(this.importedJSON);
}

_ParseJSON() {
    return fetch(this.URL)
        .then(response => response.json())
        .then((responseJSON) => {
            const { statusCode, data } = responseJSON;
            console.info("_PARSE");
            console.info(responseJSON);
            return responseJSON;
        })
        .catch((e) => {
            console.error(e);
        })
}

set URL(_newUrl) { this.constructor.URL = _newUrl; }
get URL() { return this.constructor.URL; }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-10 03:33:29

你说过了

在_ParseJSON中 console.info正确地打印出我想要的JSONObject,但是在获取之外,不可能重新构造JSON

这是因为您不能在promise中返回值。

教训是异步函数不返回(或至少不可靠地返回)

如果您希望在异步函数之后发生某些事情,则需要在异步函数内调用它

您可以使用

代码语言:javascript
复制
_ParseJSON() {
    return fetch(this.URL)
        .then(response => response.json())
        .then((responseJSON) => {
            const { status, data } = responseJSON;
            console.info("_PARSE");
            console.info(responseJSON);
            // set the value you want as an example
            this.importedJSON = responseJSON;
        })
        .catch((e) => {
            console.error(e);
        })
}

相反,

希望这能对你有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50777686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档