我刚刚开始使用 hapi.js (^17.3.1) 和 mongodb (^3.0.7),以及异步 js 代码。
在路由处理程序中,我试图从数据库中检索数据。作为测试,我将一个字符串存储在通过循环访问数据库集合记录构建的变量“s”中。浏览器的预期输出是
开始 dbInfo1 dbInfo2 dbInfoN 结束
我已经尝试了这段代码的各种版本:
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 错误
调试:内部、实现、错误
错误:处理程序方法没有返回值、承诺或抛出错误
dbInfo1
dbInfo2
dbInfoN
如果我返回承诺本身或从承诺内部返回,或者我得到
开始结束
如果我从承诺之外返回,则在浏览器中。
无论哪种情况,console.log 语句都会打印出 dbInfos 输出。
我尝试了 async 和 await 的不同放置、包含和省略,结果几乎相同。我还尝试使用“new Promise(...”) 将 getRoutes 中返回的内容包装到显式 Promise 中。在这种情况下,控制台会记录 dbInfos,但浏览器挂起。
在返回变量 s 之前,如何等待“foreach”函数?
最后!得到它与此代码的工作:
module.exports = {
method: 'GET',
handler: function (request, reply) {
return getRoutes();
}
}
function getRoutes() {
const mongo = require('mongodb').MongoClient;
const mongoUrl = "mongodb://127.0.0.1:27017/";
return mongo.connect(mongoUrl)
.then(async function(client) {
var s = "start";
var documents = await
client.db("dbName").collection("collectionName")
.find()
.toArray();
for (const doc of documents)
s += " | " + await doc.item;
return s + " end";
});
}
问题是我认为由于“getRoutes”被标记为“async”,“.then”中的内容也是异步的。但我真的需要将“函数(客户端)”标记为“异步”。我还需要停止使用“forEach”并在集合上使用更传统的迭代。
我之前实际上已经将“function(client)”标记为“async”,但这是出于盲目的反复试验,所以我从未正确使用过“await”。直到我阅读了 Anton Lavrenov 的这篇博客,我才真正开始理解它。
虽然我最近才问这个问题,但在那之前我已经研究了很长时间。对我现在所处的位置真的很满意。当然,感谢@desoares 指出我在上面使用的代码版本中的愚蠢错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句