Encountering issues with an async function.
In the ../lib folder, I have a class for handling data from an API website. However, when attempting to load the API data within an async function, I encounter difficulties.
The async function does not return anything - even when creating and trying to return an object within the async function.
Instead, I consistently receive an empty object {} whenever the function is called.
Below is the code snippet:
private procurr(obj){
// Processing begins here
const mainObj = async function(ob) {
var robj : any = [];
var item = {};
var i : number = 0;
var total : number = 10;
try{
for(item in ob){
let res2 = await axios.get('https://hacker-news.firebaseio.com/v0/item/'+item+'.json');
const obji = await res2.data;
var word : string = this.help.mode(this.help.words(obji.title));
if(word.length > 0){
if(i < total){
robj[i] = (this.help.inArr(word, robj)) ? this.help.incScore(robj[i]) : {'word': word, 'score':1};
// increment
i++;
}
}
}
}catch(error){
console.error(error);
}
// return JSON.parse(robj);
return ob;
}
// exports.mainObj = mainObj;
// Return statement
// return obj;
return mainObj(obj);
}
EDITED:
I am calling the procurr(obj) method from q1(obj) as follows:
// Creating the question method
public q1(obj) : any {
var last25 = this.help.last25(obj);
// Returning
return this.procurr(last25);
}
Calling the q1(obj) method from getStaticProps():
export async function getStaticProps() {
const postClass = new Posts();
// Fetching data
const res = await axios.get('https://hacker-
news.firebaseio.com/v0/topstories.json');
const obj = await res.data;
const ob = JSON.stringify(postClass.q1(obj));
return {
props: { ob }
}
}
The API call returns an object containing post IDs from Hacker News website.