【问题标题】:Why Async function in Next JS returns empty object in my Typescript code?为什么 Next JS 中的异步函数在我的 Typescript 代码中返回空对象?
【发布时间】:2022-01-09 21:02:22
【问题描述】:

我在使用异步函数时遇到了一些问题。

我的 ../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 的对象

【问题讨论】:

  • 但是为什么即使我用我的名字返回对象而不是从提取中返回空对象
  • return await mainObj(obj); 是异步的,需要等待
  • 如果我在异步函数之外调用 await 它请求我将父方法也转为异步
  • Await 将要求我将 procurr 功能也转为异步,当我这样做时,我开始在 procurr 中遇到同样的问题
  • @JeremyThille No need for that,可以直接return 承诺。这部分代码按原样工作。

标签: javascript typescript api next.js


【解决方案1】:

你有一串异步方法,但在底部你忘了await它。如果你尝试 JSON.stringifyPromise 你会得到一个空对象

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));

【讨论】:

    猜你喜欢
    • 2018-07-23
    • 2020-08-30
    • 1970-01-01
    • 2021-12-30
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2021-08-17
    相关资源
    最近更新 更多