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?