javascript - react native : Write value to variable outside of a inner function

标签 javascript android json react-native fetch

我刚开始使用 React Native,目前正在为我们的项目开发 couchdb API。我正在用 fecht 做我的休息请求。但是在内部函数中,我无法将我的响应文本 (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;
}

在我的函数结束时,变量 result 的值仍然是“getDocument failed”,而不是我的 json 字符串。 我已经尝试通过调用另一个函数将我的响应文本存储在其他地方,但效果不佳。

最佳答案

您需要了解异步与同步 - 在上面的代码中,您正在运行一系列同步语句 - 变量 result 的赋值document,然后运行异步语句:fetch,然后使用 Alertreturn 运行另外两个同步语句。

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

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

 _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
}

或者,如果您在组件中执行此操作,您可以简单地设置状态而不是运行回调:

this.setState({
    data: result
})

关于javascript - react native : Write value to variable outside of a inner function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533318/

相关文章:

android - 从 libs/添加一个 jar 文件到 Android.mk

json - ElasticSearch:在字段中包含字段的日期范围

javascript - 在 Highcharts 中手动设置 y 轴最小值和最大值以及放大行为

javascript - Nodejs,如何重构数据的响应?

javascript - 无需ajax或iframe的回调(纯代码)

java - 在 Java/Android 中向 String 类添加一个方法,就像在 iPhone 上的 objective-c 中的类别一样

javascript - 如何将多个属性导入javascript中的对象?

android - 微调器的自定义 ArrayAdapter : drop down view not working properly

java - Json异常类型错误

ios - 如何使用 nsjsonserilization 添加登录 api?