I'm having some problems with async function.
I have a class in my ../lib folder for processing data from an API website but i ran into problems when i try to load the api data in async function.
The async function dont even return anything, not even when i create object and try to return it inside the async function
All i get is {} empty object every time i call the function
Here is my code:
private procurr(obj){
// Here we start processing
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;
// Here we return
// return obj;
return mainObj(obj);
}
EDITED:
I'm calling the procurr(obj) from q1(obj) like so:
// Here we create question question method
public q1(obj) : any {
// var topIDs = this.help.obj2Arr(obj);
var last25 = this.help.last25(obj);
// Here we return
return this.procurr(last25);
// return last25;
}
I'm calling the q1(obj) method from getStaticProps() like so
export async function getStaticProps() {
const postClass = new Posts();
// Here we fetch data
const res = await axios.get('https://hacker-
news.firebaseio.com/v0/topstories.json');
const obj = await res.data;
// const obj = await JSON.parse(JSON.stringify(res.data));
// Here we check route request
const ob = JSON.stringify(postClass.q1(obj));
// ob = JSON.parse(postClass.q2(obj));
// ob = JSON.parse(postClass.q3(obj));
return {
props: { ob }
}
}
The API call returns a object containing posts ids from hackernews website
CodePudding user response:
You have a string of async methods, but at the bottom you forgot to await
it. If you try to JSON.stringify
a Promise
you will get an empty object
const p = new Promise(resolve => resolve({foo:"bar"}));
console.log(JSON.stringify(p)) // Not {foo:"bar"} as you might expect
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The method you're calling it from is already async
so just add an await
const ob = JSON.stringify(await postClass.q1(obj));