Tengo algunos problemas con la función asíncrona.
Tengo una clase en mi carpeta ../lib para procesar datos de un sitio web de API, pero tuve problemas cuando intento cargar los datos de API en la función asíncrona.
La función asíncrona ni siquiera devuelve nada, ni siquiera cuando creo un objeto e intento devolverlo dentro de la función asíncrona
Todo lo que obtengo es {} objeto vacío cada vez que llamo a la función
Aquí está mi código:
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); }EDITADO:
Estoy llamando a procurr(obj) desde q1(obj) así:
// 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; }Estoy llamando al método q1(obj) desde getStaticProps() así
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 } } }La llamada API devuelve un objeto que contiene ID de publicaciones del sitio web de hackernews
Tiene una cadena de métodos asíncronos, pero en la parte inferior olvidó await . Si intenta JSON.stringify a Promise , obtendrá un objeto vacío
const p = new Promise(resolve => resolve({foo:"bar"})); console.log(JSON.stringify(p)) // Not {foo:"bar"} as you might expect El método desde el que lo está llamando ya es async , así que solo agregue una await
const ob = JSON.stringify(await postClass.q1(obj));