-3

This is the code I am using to grab data:

let user = await axios.get(`${base_api_url}/users/${req.params.username}`, options)
let events = await axios.get(`${base_api_url}/users/${req.params.username}/events`, options)

res.json({
    success:true,
    user: user.data,
    events: events.data
})

I like how neat this is but the downside to this is that I can't handle errors. Any ideas?

3
  • 2
    Why can't you handle errors?
    – Kevin B
    Jan 20, 2020 at 22:34
  • Clearly im asking this question because I didnt know the right way to do it.
    – Syn
    Jan 20, 2020 at 22:39
  • 1
    to me it seemed like you were unaware that error handling even existed for async/await... but that's pretty easy to find on the web... so i didn't want to assume you didn't look for it.
    – Kevin B
    Jan 20, 2020 at 22:43

1 Answer 1

1

You just need try/catch around your await as that's how you catch promise rejections when using await.

try {
    let user = await axios.get(`${base_api_url}/users/${req.params.username}`, options)
    let events = await axios.get(`${base_api_url}/users/${req.params.username}/events`, options)

    res.json({
        success:true,
        user: user.data,
        events: events.data
    })
} catch(e) {
    console.log(e);
    // decide what to do here when you get an error
    res.status(500).send("axios error")'
}

Run Requests In Parallel

FYI, you don't need to sequence your two axios calls one after the other. You could likely speed things up a bit with Promise.all():

 Promise.all([
     axios.get(`${base_api_url}/users/${req.params.username}`, options),
     axios.get(`${base_api_url}/users/${req.params.username}/events`, options)
 ]).then(([user, events]) => {
    res.json({
        success:true,
        user: user.data,
        events: events.data
    });
 }).catch(err => {
    console.log(err);
    res.sendStatus(500);
 });

or:

try {
     let [user, events] = await Promise.all([
         axios.get(`${base_api_url}/users/${req.params.username}`, options),
         axios.get(`${base_api_url}/users/${req.params.username}/events`, options)
     ]);
     res.json({
         success:true,
         user: user.data,
         events: events.data
} catch(err) {
     console.log(err);
     res.sendStatus(500);
}
1
  • 1
    @Syn - Also, see how you can run these requests in parallel to get better performance. Or, you could use await with Promise.all() too, but it didn't seem necessary here.
    – jfriend00
    Jan 20, 2020 at 22:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.