我刚刚开始使用 hapi.js (^17.3.1) 和 mongodb (^3.0.7) 以及异步 js 代码。
在路由处理程序内,我尝试从数据库检索数据。作为测试,我将字符串存储在通过循环数据库收集记录构建的变量“s”内。浏览器的预期输出是
start dbInfo1 dbInfo2 dbInfoN end
我尝试过此代码的各种版本:
module.exports = {
method: 'GET',
handler: async function (request, reply) {
return await getRoutes();
}
}
async function getRoutes() {
var s = "start";
const mongo = require('mongodb').MongoClient;
const mongoUrl = "mongodb://127.0.0.1:27017/";
return // I'm returning this whole thing because hapi.js says it wants a promise. (500 error)
await mongo.connect(mongoUrl)
.then(function(client) {
client.db("dbName").collection("collectionName")
.find({})
.forEach(function (record) {
console.log(record.item);
s += " | " + record.item;
});
s + " end"; // But I've tried placing "return" here (500 error)
});
// I've also tried ".then(function(s) { return s + 'end' }) here but it seems to only have the same set of options/problems manifest.
// I've also made it so that I place "return s + 'end'" here (displays "start end" with nothing in the middle).
}
我尝试将 return 语句放在不同的位置。我要么在控制台中收到 http 500 错误
Debug: internal, implementation, error
Error: handler method did not return a value, a promise, or throw an error
dbInfo1
dbInfo2
dbInfoN
如果我返回 promise 本身或从 promise 内部返回,或者我得到
start end
如果我从 promise 之外返回,则在浏览器中。
无论哪种情况,console.log 语句都会打印出 dbInfos 输出。
我尝试了 async 和 wait 的不同放置、包含和省略,结果几乎相同。我还尝试使用“new Promise(...”将 getRoutes 中返回的内容包装到显式 Promise 中。在这种情况下,控制台会记录 dbInfos,但浏览器会挂起。
如何在返回变量 s 之前等待“foreach”函数?
最佳答案
未经测试,我可以说这是错误的:
return // I'm returning this whole thing because hapi.js says it wants a promise. (500 error)
await mongo.connect(mongoUrl)
.then(function(client) {
client.db("dbName").collection("collectionName")
.find({})
.forEach(function (record) {
console.log(record.item);
s += " | " + record.item;
});
s + " end"; // But I've tried placing "return" here (500 error)
});
return被解析为return;
return await mongo.connect(mongoUrl)
.then(function(client) {
client.db("dbName").collection("collectionName")
.find({})
.forEach(function (record) {
console.log(record.item);
s += " | " + record.item;
});
s + " end"; // But I've tried placing "return" here (500 error)
});
是正确的方法。任何 linter 都会警告您这一点。
关于javascript - 如何在 hapi.js 路由处理程序中将 mongodb 信息返回到浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50190610/