Javascript 在上一个函数完成后立即执行函数(在fetch中)
如何在第二个函数完成后立即调用该函数。我有以下代码:Javascript 在上一个函数完成后立即执行函数(在fetch中),javascript,reactjs,asynchronous,react-native,fetch,Javascript,Reactjs,Asynchronous,React Native,Fetch,如何在第二个函数完成后立即调用该函数。我有以下代码: import { handleTokenExpiration } from '../../utils/tokenExpiration' handleClick(){ fetch(someURL, { method: "PUT", headers: { Authorization: `Bearer${token}`, }, body: JSON.stringify({
import { handleTokenExpiration } from '../../utils/tokenExpiration'
handleClick(){
fetch(someURL, {
method: "PUT",
headers: {
Authorization: `Bearer${token}`,
},
body: JSON.stringify({
note: this.state.text,
})
})
.then((response) => response.json())
.then((responseData) => {
if (responseData.success) {
Alert.alert(
'Thanks!',
[
{text: 'OK'}
],
{ cancelable: false }
)
}
else{
if(responseData.mvMessages[0].message === "your token is expired"){
handleTokenExpiration(this.props.token)
this.handleClick()
}
else{
switch (responseData.mvMessages[0].key) {
case 'note':
this.setState({
userNoteError: responseData.mvMessages[0].message,
})
break;
case 'note2':
this.setState({
userInputError: responseData.mvMessages[0].message,
})
break;
default:
this.setState({
userLastError: responseData.mvMessages[0].message,
})
}
}
}
})
.catch(error => {
console.log(error)
})
}
基本上,当令牌过期时,应该调用这两个函数handleTokenExhilation(this.props)
和this.handleClick()
第一个函数处理令牌过期,第二个函数调用同一个函数(使用有效令牌)。这是可行的,但问题是,由于异步行为,这两个函数都会被多次调用
如何等待handleTokenExhilation(this.props)完成,然后运行this.handleClick()
类似于我们希望在setState完成后立即运行函数的情况:
this.setState({
FirstName: this.props.firstName
}, () => this.calledRightAfterSetStateisFinished())
但是在这种情况下,一个接一个的函数。那么,以下函数有什么问题呢:
handleTokenExpiration(this.props.token, () => {
this.handleClick();
});
在handleTokeNextriversion
中,您有:
export default function handleTokenExpiration(token, callback) {
// ... do whatever you need to do
callback();
}
好吧,你怎么了:
handleTokenExpiration(this.props.token, () => {
this.handleClick();
});
在handleTokeNextriversion
中,您有:
export default function handleTokenExpiration(token, callback) {
// ... do whatever you need to do
callback();
}
如果使用ES7,请尝试签出
async
和wait
。如果使用ES7,请尝试签出async
和wait
。