如何在 expressjs 路由器中使用 Async/Await?

Ojo*_*eun 0 javascript asynchronous mongoose node.js express

我一直在与有关 Async/Await 的问题作斗争,我对 Nodejs 比较陌生。我有一个存储库,我直接连接到我的 mongodb 集合以检索它的一些数据,但是当我将控制器连接到这个存储库时,我得到一个空响应。请在下面查看我的代码:-

同步存储库.js

const mongoose = require('mongoose');

exports.ItemRepo = async (limit) => {
  try {
     await mongoose.connection.db.collection('items_1087342')
        .find({}, {timeout: false}).limit(limit).toArray((err, results) => {
            // results.forEach(e => {
            //     console.log(e.item_id);
            // }); //This works well
            return results;
        });
 } catch (e) {
    throw Error('Error Loading Data:- ' + e.message);
 }
};
Run Code Online (Sandbox Code Playgroud)

同步控制器.js

const syncRepo = require('../../../Repositories/Sync/SyncRepository');

exports.getItem = async (req, res) => {
  try {
     await syncRepo.ItemRepo(7)
        .then(element => {
            console.log(element);
           return res.json(element); //This return null
        });
    // return await res.json(await syncRepo.ItemRepo(7));
 } catch (e) {
    return res.status(400).json({ status: 400, message: e.message });
 }
};
Run Code Online (Sandbox Code Playgroud)

Jer*_*lle 5

您正在混合使用async/await传统的 Promise 语法。尝试这个 :

同步存储库.js

const mongoose = require('mongoose');

exports.ItemRepo = limit => {
     return mongoose.connection.db.collection('items_1087342')
        .find({}, {timeout: false})
        .limit(limit)
        .exec() // see @Enslev's explanation in the comments
};
Run Code Online (Sandbox Code Playgroud)

同步控制器.js

const syncRepo = require('../../../Repositories/Sync/SyncRepository');

exports.getItem = async (req, res) => {
  try {
     let element = await syncRepo.ItemRepo(7)
     return res.json(element);
 } catch (e) {
    return res.status(400).json({ status: 400, message: e.message });
 }
};
Run Code Online (Sandbox Code Playgroud)