React Native:将值写入内部函数之外的变量

时间:2016-05-30 20:32:37

标签: javascript android json react-native fetch

我刚开始做反应本机,目前正在为我们的项目开发一个couchdb api。我正在用fecht做我的休息请求。但是在内部函数中,我无法将我的responsetext(json)写入我想要返回的变量。

_getDocument(pID)
{
    var result = "getDocument failed"

    var document = "https://"
        + this.connection.user + ":"
        + this.connection.password + "@"
        + this.connection.server + "/"
        + this.connection.database + "/"
        + pID;

    fetch(document)
        .then((response) => response.text())
        .then((responseText) => {

            result = responseText;
            Alert.alert('Fetch', result , [{text: 'ok'}])

        }).catch((error) => {
        console.warn(error);
    });

    Alert.alert('_getDocument', result , [{text: 'ok'}])

    return result;
}

在我的函数结束时,变量结果仍然具有值" getDocument失败"而不是我的json字符串。 我已经尝试通过调用另一个函数将我的响应文本存储在其他地方,但是它也不起作用。

1 个答案:

答案 0 :(得分:1)

您需要了解异步与同步 - 在您的代码中,您正在运行一系列同步语句 - 变量hdfs dfs -setrep -R 2 /data/2016result的分配,然后运行异步语句:document,然后使用fetchAlert再运行两个同步语句。

我们将return方法称为异步,因为它在后台运行,并且不会通过使用您正在使用JS promises的两个fetch()语句来中断代码执行。当获取请求完成处理时,将执行您传递的函数(then()和第二个回调)。这对API调用很有意义,因为它可能需要一些时间。

您只需要重新考虑代码的结构,可能在promise promise函数中使用回调:

response.text()

或者,如果你在一个Component中执行它,你可以简单地设置状态而不是运行回调:

 _getDocument(pID) {
    // Variable declarations...

    fetch(document)
        .then((response) => response.text())
        .then((responseText) => {

        result = responseText;
        Alert.alert('Fetch', result , [{text: 'ok'}])

        this.fetchCompleted(result)

    }).catch((error) => {
        console.warn(error);
    });
}

fetchCompleted (result) {
    Alert.alert('_getDocument', result , [{text: 'ok'}])
    // Do something with result
}