I'm hoping somebody can point out the error of my ways here.
I have two functions at the moment. One is getData and it's an async function that simply makes an API call requesting data. The second function is getRandomCategories that encapsulates the getData function call and holds the value of that async operation in a variable called res
. The rest of the code within getRandomCategories manipulates the response data to an array of numbers where each number represents a category.
When I use the debugger statement in the getRandomCategories function (right before the return statement within the try block) I'm getting the data type I'm expecting from my variable named apiCallCategoryArray
- it's an array of numbers each representing a category. Life is good.
Here's the rub. When I call getRandomCategories expecting the dataArray
variable (at the bottom of the code snippet) to hold an array of numbers - I'm getting a Promise back with its state pending??
I'm not understanding why the value for apiCallCategoryArray
variable is showing up as my expected value using the debugger (and thus I'm returning it within the function) but I'm not able to access that value when I call the function. Why am I getting a Promise back with a pending state? What am I missing?
Here's my code below:
async function getData(endpoint, query, value) {
return await axios.get(
`http://jservice.io/api/${endpoint}?&${query}=${value}`
)
}
// 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);
debugger// the value is what I'm expecting an array of numbers with length = 6
return apiCallCategoryArray
} catch (err) {
console.log(err);
}
}
//Solution one: Does not work. I'm getting a promise back instead of an array of numbers
const dataArray = getRandomCategories()
console.log(dataArray) // Promise { <state>: "pending" }
// expected return value [12231, 12344, 343245,124041, 12344, 348855] array of numbers
// Solution two: Does not work either. I'm still getttng a promise back instead of an array of numbers
const dataArray2 = getRandomCategories().then((array) => {
return array
})
console.log(dataArray2) // Promise { <state>: "pending" }
// expected return value [12231, 12344, 343245,124041, 12344, 348855] array of numbers
My objective is for my dataArray variable to hold an array of numbers (not a Promise with pending) returned by calling getRandomCategories(). So I can use this value for other functions in my code.
Thanks in advance for your time and responses.