简体   繁体   中英

Null return value from a nested async function

How does this function returns null? is it because of the variable scope or execution time of the functions?

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. so one convenient way to solve this is to make a callback function from the async function.

Sorry I am not a js guy so I can't actually post code but I think you got the idea..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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