I am here because i am having troubles debugging my app. It's very annoying not see why my app crashes. I was using promises (with then/catch blocks) but i get on the necessity of using async/await.
I have a method where i do multiple await on it. The problem here is that if my app crashes because any reason i never know whats the problem on it. I have described the block like this:
static async processCSGOGroupsAndUsers (groupName) {
try{
const csgoApiData = await csgoApi(groupName);
const parsedData = await xmltojson(csgoApiData);
const id = parsedData.memberList.groupID64;
//const members = await retrieveMembers(groupName, parsedData.memberList.memberCount);
const totalUsers = await UsersService.processCSGOUsers(id, parsedData);
const csgoGroup = {
name: parsedData.memberList.groupDetails.groupName,
siteUrl: parsedData.memberList.groupDetails.groupURL,
id,
totalUsers
};
await GroupsDao.save(csgoGroup);
}catch (err){
return err;
}
}
static async processCSGOUsers (groupId, parsedData) {
try{
let steamIdsArr = [];
const usersSteamIdsObj = parsedData.memberList.members.steamID64;
Object.keys(usersSteamIdsObj).forEach(key => {
//if (steamIdsArr.length < 2) // TODO csGOBackPackAPI don't let me do more than 50 request per hour
steamIdsArr.push({
steam_group_id_64: groupId,
steam_id_64: usersSteamIdsObj[key]
});
});
//const filteredUsers = await UserService.filterUsersByInventoryValue(steamIdsArr);
UsersDao.saveUsers(steamIdsArr);
} catch(err){
console.log(err);
return err;
}
}
static processCSGOGroups(req, res){
GroupService
.processCSGOGroupsAndUsers(req.body.group)
.then( () => res.status(200).end())
.catch( error => res.status(400).send(error));
}
Is there a better approach than mine's?
I created an NPM package to help with situations like this. https://www.npmjs.com/package/@simmo/task
The following shows example usage. The idea is that it should help remove try/catch replacing with conditional logic - hopefully helping to make everything a little more readable! :)
import task from '@simmo/task'
const { error, data } = await task(fetch('/some-api'))
if (error) {
// Failure
console.error(error)
} else {
// Success
console.log(data)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.