小编Ojo*_*eun的帖子

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

我一直在与有关 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 …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous mongoose node.js express

0
推荐指数
1
解决办法
1885
查看次数

标签 统计

asynchronous ×1

express ×1

javascript ×1

mongoose ×1

node.js ×1