问题描述
我将以下代码作为我的 React Native 组件之一中的 Button 的一部分。观察如何没有 .catch 来处理来自服务器的可能的“无结果”情况;它是用 if 语句处理的(例如:else if (acceptMatchRequestData['status']==='failure') 我正试图摆脱它。
await acceptMatchRequest(match['matchId'],userId,getUserInfoData[0]['ratings'][matchType])
.then(acceptMatchRequestData => {
if (acceptMatchRequestData['status']==='success') {
setMatchInvites(prevstate => {
return prevstate.filter((observation,i) => observation['matchId'] !== match['matchId'])
})
setMatchScreenParentState('loading')
sendToUserDeviceNotification('matchFound',match['matchedUserId'])
} else if (acceptMatchRequestData['status']==='failure') {
Alert.alert('',acceptMatchRequestData['message'])
}
})
export async function acceptMatchRequest(matchId,rating) {
console.log('Attempting to accept match request');
info = { matchId,rating }
const firebaseIdToken = await AsyncStorage.getItem('@firebaseIdToken')
const requestOptions = {
method: 'POST',headers: { 'Content-Type': 'application/json','Authorization': 'Bearer ' + firebaseIdToken },body: JSON.stringify(info)
};
const response = await fetch(ngrokOrLocalhost + '/acceptmatchrequest',requestOptions)
const data = await response.json()
return data
}
和服务器代码:
router.post('/acceptmatchrequest',async (req,res) => {
const { matchId,rating } = req.body;
const results = await Match.find({ 'usersInfo.userId': userId,'matchRecords.matchConfirmed': { $nin: [true] } }).limit(5)
if (results.length===5) {
res.status(400).json({'status': 'failure','message': 'You already have 5 active matches. Please finish a match first before you can accept this match.'})
} else {
var filter2 = { '_id': matchId }
var update2 = { 'isCustomrequest_IsAccepted': true,'$push': { 'usersInfo': { 'userId': userId,'location': { 'type': 'Point','coordinates': [0,0] },'rating': rating } } }
var response2 = await Match.findOneAndUpdate(filter2,update2,{ new: true,sort: { 'matchCreatedTimestamp': 1 } })
if (response2) {
// Document was updated
res.status(200).json({'status': 'success','message': 'Match request was accepted successfully'})
} else {
console.log('Match request was not accepted successfully');
res.status(400).json({'status': 'failure','message': 'Match request was not accepted successfully'})
}
}
})
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)