反应本地获取承诺.then()不会立即执行 [英] React Native fetch promise .then() not executing immediately
问题描述
我正在使用React Native为iOS和Android构建一个应用程序.在这里,只要轻按一下按钮,我就从外部函数中调用提取函数.fetch函数将POST请求发送到链接,并获取JSON响应(JSON是正确的,已通过Postman进行了各种测试).
I'm using React Native to build an app for iOS and Android. In there, I'm simply calling fetch function from an external function once a button is tapped. The fetch function sends a POST request to a link and gets back a JSON response (JSON is correct, tested with Postman in various ways).
问题在于.then()之后的代码不会立即执行,而是在我点击屏幕或使用导航返回或执行某种较小的操作之后执行.这是我使用的代码:
The issue is that the code after .then() is not executed immediately, but after I tap on the screen or go back using the navigation or perform some sort of minor actions. Here's the code that I used:
从功能中调用代码
verify() {
this.setState({
pressed: true
});
var self = this;
var theURL = "<URL>"; //Removed for question
fetch(theURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
uidOrEmail: this.state.email,
code: this.state.value
})
})
.then(res => res.json())
.then(function(data) {
console.log(data); //PROBLEM: This doesn't execute immediately
}
BINDING 我也像这样在构造函数中绑定此函数:
BINDING I'm also binding this function in the constructor like this:
constructor(props) {
super(props);
console.log(this.props.navigation.state.params.email);
this.state = {
email: props.navigation.state.params.email,
value: '',
pressed: false
};
this.verify = this.verify.bind(this);
}
从用户界面调用功能
<Button
disabled={this.state.pressed}
onPress={this.verify}
>{!this.state.pressed ? 'Verify' : 'Verifying...'}</Button>
总结:提取功能无法立即解决promise.
To summarize: Fetch function not resolving promise immediately.
编辑
更多信息:
提取链接实际上是Firebase函数的链接.该函数如何返回:
The fetch link is actually a Firebase function's link. How that function is returning:
response.status(200).send({status: 200, token: "ABC"});
推荐答案
fetch
将返回一个 Promise
对象,由 then()添加的回调
将在诺言成功之后被调用.如果承诺失败,则将调用 catch()
添加的回调.
fetch
will return a Promise
object, the callbacks added by then()
will be called after the promise is success. If the promise failed, the callback added by catch()
will be called.
您可以在 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise .
这篇关于反应本地获取承诺.then()不会立即执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!