0

I set up a server using node.js and Express and I am using this function to get the main categories of a website from an API.

function getMainCategories() {
    got(`${base_url}/categories/parent/root`, { searchParams: { secretKey: `${secretKey}` } })
        .then(response => {

            // main categories
            let mains = JSON.parse(response.body);
            console.log(mains); // works
            return mains;
        })
        .catch(error => {
            console.log(error.response.body);
            res.status(404).end();
        });
    }

Inside the function everything works fine. However, for example, when I use getMainCategories() somewhere else to render a page, and log it in that function, it shows undefined.

router.get('/categories', function (req, res, next) {

    const mains = getMainCategories();
    console.log(mains); // undefined

    // some code
});

When I try the following log in there, that's what it logs:

console.log(JSON.parse(response.body)); // Promise { undefined }

Before this I was making the request manually in the second function and it worked. Why does it work only inside .then() and how can I also use it in the rest of the code?

spiderweps
  • 11
  • 1
  • 3
    There's no `return` statement in your function. Just add `function getMainCategories() { return got(// ...`. – mbojko Jul 29 '20 at 09:09
  • 2
    @mbojko Is correct, but note that this means `getMainCategories` returns a promise, and you need to do `getMainCategories().then(mains => console.log(mains))`… – deceze Jul 29 '20 at 09:12

0 Answers0