DEV Community

Discussion on: How to Return multiple functions and values while working with REST APIs (Part 1)

Collapse
 
leandroandrade profile image
Leandro Andrade

Thanks for this article. Do you have any particular reason for using "q" library instead a native modules like Promise? I question this because I had the same result using Promise.all instead is using "q" library. Other insigth is change Promise.all to Promise.allSettled that allow us to handle errors.

Below the code:

const axios = require("axios");
const app = require("express")();

app.get("/chuck-norris", async (req, res) => {
    try {
        const promises = ["https://api.chucknorris.io/jokes/random", "https://api.chucknorris.io/jokes/categories"]
            .map(url => axios.get(url));
        const result = await Promise.all(promises);

        const [jokeResponse, categoryResponse] = result;
        const { data: joke } = jokeResponse;
        const { data: category } = categoryResponse;

        const jokeData = joke.value;
        if (!jokeData) {
            res.send({ message: "Value of joke is not available" });
        }

        if (!category) {
            res.send({ message: "Category is not available" });
        }

        const random = Math.floor(Math.random() * 16);
        const response = {
            status: "success",
            message: "Data fetched",
            data: {
                joke: jokeData,
                categories: category[random]
            }
        };

        return res.json(response);
    } catch (err) {
        return res.json({ message: err });
    }
});

const listener = app.listen(8088, () => {
    console.log("Your app is listening on port " + listener.address().port);
});

Enter fullscreen mode Exit fullscreen mode
Collapse
 
olufemi profile image
Olufemi obafunmiso • Edited

Hi Leandro,

This is part 1.

I did mentioned that in part 2, we'll not be using the q library on line 6 of this article.

I will Publish Part 2 very soon.

I explained there how to achieve this with Javascript native functions.

Thank you for taking out time to read this article.