问题返回异步函数中的提取第2部分

时间:2020-10-20 20:13:05

标签: javascript react-native api fetch

我目前遇到问题,我希望能够返回所获取的内容,例如:

#initializing logger 
#setup of logger
def setLogger(logfile_name):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(message)s')
    file_handler = logging.FileHandler(logfile_name)
    file_handler.setFormatter(formatter)
    stream_handler = logging.StreamHandler()
    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)
    return logger

但我目前正在收到此消息:

{"data": [{"account_id": 134519399, "account_url": "Pseudo", "ad_type": 0, "ad_url": "", "animated": false, "bandwidth": 110238, "datetime": 1603190775, "deletehash": "Mg3FROsdfPF7N", "description": null, "edited": "0", "favorite": false, "has_sound": false, "height": 368, "id": "3HzN2Ye", "in_gallery": false, "in_most_viral": false, "is_ad": false, "link": "https://i.imgur.com/lbWS8uo.jpg", "name": "unnamed.jpg", "nsfw": null, "section": null, "size": 55119, "tags": [Array], "title": null, "type": "image/jpeg", "views": 2, "vote": null, "width": 512}], "status": 200, "success": true}

这是我的代码:

{"_U": 0, "_V": 0, "_W": null, "_X": null}

然后在此类中调用我的函数:

export default async function FetchImage(access_token) {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + access_token);

var formdata = new FormData();

var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
};

try {
    const response = await fetch("https://api.imgur.com/3/account/me/images", requestOptions)
    // console.log(await response.text());
    return response.json
}
catch (err) {
    console.log('fetch failed', err);
}
}

我看了这些解决方案:

How do I return the response from an asynchronous call?

async/await implicitly returns promise?

但是我仍然无法解决我的问题,

如果有人可以帮助我

谢谢!

3 个答案:

答案 0 :(得分:0)

response.json()也是Promise。因此,您应该在其前面附加await

export default async function FetchImage(access_token) {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + access_token);
myHeaders.append("Content-Type", "application/json");

var formdata = new FormData();

var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
};

try {
    const response = await fetch("https://api.imgur.com/3/account/me/images", requestOptions)
    // console.log(await response.text());
    return await response.json()
}
catch (err) {
    console.log('fetch failed', err);
}
}

答案 1 :(得分:0)

好吧,@ Prime,我刚刚看到,我的解决方案之后又产生了同样的问题

 async _getData() {
    try {
        this.state.test = await FetchImage(this.props.navigation.state.params.access_token);
        console.log(this.state.test.data[0]["link"])
        return (this.state.test)

    } catch (error) {
        console.error(error);
    }
    // console.log(res)

}

我在这里给他打电话:

render() {
        try {
            console.log(this._getData())
            
        } catch (error) {
            console.error(error);
        }
        console.log("ici = " + this.props.test)
        return (
            <>
                <View>
                    <Text>access_token:</Text>
                </View>
                <View style={styles.buttonFav}>
                    <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FavNav" onPress={() => this.props.navigation.navigate('FavNav')}></Button>
                </View>
                <View style={styles.buttonFind}>
                    <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FindNav" onPress={() => this.props.navigation.navigate('FindNav')}></Button>
                </View>
            </>
        )
    }
}

但是,当我尝试使用存储在“ this.state.test”中的内容时,它是“未定义的”。

console.log(this._getData())显示此{"_U": 0, "_V": 0, "_W": null, "_X": null}

我很绝望:'(

答案 2 :(得分:0)

好吧,我找到了解决方案,我必须对收到的内容进行setState

async componentDidMount() {
        try {
            let res = await FetchImage(this.props.navigation.state.params.access_token);
            this.setState({ test: res })
        } catch (error) {
            console.error(error);
        }
    }

我将其放在componentDidMount()函数中,以使setState不循环。

谢谢大家,非常感谢@Prime。