我在使用異步函式時遇到了一些問題。
我的 ../lib 檔案夾中有一個類用于處理來自 API 網站的資料,但是當我嘗試在異步函式中加載 api 資料時遇到了問題。
異步函式甚至不回傳任何東西,甚至當我創建物件并嘗試在異步函式中回傳它時也不回傳
每次呼叫該函式時,我得到的只是 {} 空物件
這是我的代碼:
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);
}
編輯:
我從 q1(obj) 呼叫 procurr(obj) 像這樣:
// 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;
}
我像這樣從 getStaticProps() 呼叫 q1(obj) 方法
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 }
}
}
API 呼叫回傳一個包含來自hackernews 網站的帖子ID 的物件
uj5u.com熱心網友回復:
您有一系列異步方法,但在底部您忘記了await它。如果你嘗試JSON.stringifyaPromise你會得到一個空物件
const p = new Promise(resolve => resolve({foo:"bar"}));
console.log(JSON.stringify(p)) // Not {foo:"bar"} as you might expect
您正在呼叫它的方法已經async如此,只需添加一個await
const ob = JSON.stringify(await postClass.q1(obj));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373521.html
標籤:javascript 打字稿 接口 下一个.js
上一篇:用于從回呼url接收資料的API
