Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140071

How to work with Async/Await in expressjs router?

$
0
0

I've been battling with an issue concerning Async/Await, I'm relatively new to Nodejs. I have a repository where I connect directly to my mongodb collection to retrieve some data it but when I connect my controller to this repository, I get a nulled response. Please checkout my code below:-

SyncRepository.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);
 }
};

SyncController.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 });
 }
};

Viewing all articles
Browse latest Browse all 140071

Trending Articles