>我有以下代码
async _onPress() {
NetInfo.isConnected.fetch().then(isConnected => {
if (isConnected) {
fetch(apiURL + '/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.props.username,
password: this.props.password
})
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.status === 'success')
//I am getting error here
await AsyncStorage.setItem('token', responseJson.token);
//moving on to the main screen if server return success
Actions.MainScreen();
} else {
Toast.show({
text: "Wrong username or password!",
type: "danger"
});
}
})
.catch((error) => {
console.log(error);
});
} else {
Toast.show({
text: "Please Connect To Internet",
type: "danger"
});
}
});
}
我正在尝试使用 AsyncStorage 保存从 API 服务器收到的令牌。出现以下错误
Expression statement is not assignmentor call
和RefrenceError:await is not defined
当我尝试在该位置使用等待时。
但是当在函数的开头使用相同的代码时,我没有收到任何错误。
我不知道出了什么问题。异步等待中不允许吗?我对这些不太熟悉。
如果_onPress
调用了一些异步函数,并且你想等待所有函数完成,你必须在每个函数前面放置一个"await"。此外,每个异步函数(包括异步回调函数(也必须async
声明。
完整代码:
async _onPress() {
**await** NetInfo.isConnected.fetch().then(**async** (isConnected) => {
if (isConnected) {
**await** fetch(apiURL + '/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.props.username,
password: this.props.password
})
})
.then((response) => response.json())
.then(**async** (responseJson) => {
if (responseJson.status === 'success') {
**await** AsyncStorage.setItem('token', responseJson.token);
Actions.MainScreen();
} else {
Toast.show({
text: "Wrong username or password!",
type: "danger"
});
}
})
}
})
}