I'm not getting the return value I'm expecting from an async function when I try to save the return value in a variable. When I step into my function and inspect the return value with the debugger statement (an array of numbers representing categories i.e. [123, 423, 874, 999, 234, 452]) it is what I expect it to be.
I am using the run() function as that I'm using as a wrapper for when I call the getRandomCategories() function. When I console.log(res) it is an array of ids (this is what I'm expecting)
But when I try to save the return value in a variable (const categoriesArray = run()) I'm expecting an array of ids so I can use the array for another function instead I'm getting a Promise with a pending state. What am I missing?
Here's my code:
async function getData(endpoint, query, value) {
const res = await axios.get(
`http://jservice.io/api/${endpoint}?&${query}=${value}`
);
return res;
}
// createa a function that will return 6 random categories
async function getRandomCategories() {
try {
const res = await getData('categories', 'count', 50);
const data = res.data;
const categories = filterCategoryData(data); // I'm filtering for category id with clues_count === 5
const categoryIdArr = mapCategoryIds(categories); // an array of just category Ids
const shuffledCategoryIds = shuffle(categoryIdArr);
const apiCallCategoryArray = takeFirstXItems(shuffledCategoryIds, 6);
return apiCallCategoryArray;
} catch (err) {
console.log(err);
}
}
async function run() {
const res = await getRandomCategories()
// console.log(res) logs my expected output
return res // I want it to return an array of numbers.
}
const categoriesArray = run() // I'm expecting and array of ids
console.log(categoriesArray) // Why am I not gettng an array of ids in
//my variable? Instead I get a Promise: state <pending>