我刚开始使用 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
,然后使用 Alert
和 return
运行另外两个同步语句。
我们调用 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/