我一直在与有关 Async/Await 的问题作斗争,我对 Nodejs 还比较陌生。我有一个存储库,我直接连接到我的 mongodb 集合以检索一些数据,但是当我将 Controller 连接到该存储库时,我得到一个空响应。 请查看下面我的代码:-
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 });
}
};
最佳答案
您正在混合 async/await
和传统的 Promise 语法。试试这个:
SyncRepository.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
};
SyncController.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 });
}
};
关于javascript - 如何在expressjs路由器中使用Async/Await?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60147783/