简体   繁体   English

Null 来自嵌套异步 function 的返回值

[英]Null return value from a nested async function

How does this function returns null?这个 function 如何返回 null? is it because of the variable scope or execution time of the functions?是因为变量 scope 还是函数的执行时间?

async function getBook() {
      var book;
      await libray.findONe({ cat: 1 }, {}, async (err, res) => {
        await section.findONe({ secId: res.secI }, {}, (error, result) => {
          book = result;
        });
      });
    
      book = result;
    }


return book;
}

Try this尝试这个

async function getBook() {
      const res = await libray.findOne({ cat: 1 });
      const book = await section.findOne({ secId: res.secI });
      return book;
    }

I think the problem is that you are returning from the function before the async function finishes.我认为问题在于您在异步 function 完成之前从 function 返回。 so one convenient way to solve this is to make a callback function from the async function.所以解决这个问题的一种方便方法是从异步 function 中进行回调 function。

Sorry I am not a js guy so I can't actually post code but I think you got the idea..对不起,我不是一个 js 人,所以我实际上不能发布代码,但我认为你明白了..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM