【发布时间】:2020-12-15 17:36:49
【问题描述】:
下面的代码是https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp的混合代码 和 https://stackoverflow.com/questions/49982058/how-to-call-an-async-function#:~:text=Putting%20the%20async%20keyword%20before,a%20promise%20to%20be%20resolved.
当您查看代码下方的 console.log 时,事情似乎出现了问题。我认为通过使函数异步并使用 .then 可以避免这些问题。
我希望 MongoDB 数据检索功能与 app.get 功能分开。 没有数据返回到 get 请求。我猜 app.get 代码在函数返回值之前失败并结束。我需要更正什么?
async function getLanguageTranslationData(fromLanguage, toLanguage) {
console.log("Started getLanguageTranslationData")
const databaseUrl = "mongodb://localhost:27017"
const databaseName = 'MyCompanyPOC'
mongoClient.connect(databaseUrl, function(err, conn) {
if (err) throw err;
const collectionName = "Phrases";
var dbo = conn.db(databaseName)
var query =
{ $and:
[ {masterLanguage: fromLanguage},
{localizedLanguage: toLanguage}
]
}
console.log("query=" + JSON.stringify(query));
console.log("about to retrieve data");
dbo.collection(collectionName).find(query).toArray(
function(err, result) {
if (err) throw err;
console.log("Back from mongoDB.find()")
console.log(JSON.stringify(result))
return result
conn.close()
})
})
}
app.get("/api/gettranslations/:fromLanguage/:toLanguage",
async function(req, res) {
console.log("Backend: /api/gettranslations method started: " +
" fromLanguage=" + req.params.fromLanguage +
" toLanguage=" + req.params.toLanguage)
getLanguageTranslationData(
req.params.fromLanguage,
req.params.toLanguage)
.then((arrayResult) => {
console.log("got arrayResult back from getLanguageTranslationData")
res.status(200).json(arrayResult)
console.log("Backend: End of /api/gettranslations process")
})
})
Node.JS 控制台输出:
listening on port 3001
Backend: /api/gettranslations method started: fromLanguage=en-US toLanguage=es-MX
Started getLanguageTranslationData
(node:44572) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
got arrayResult back from getLanguageTranslationData
Backend: End of /api/gettranslations process
query={"$and":[{"masterLanguage":"en-US"},{"localizedLanguage":"es-MX"}]}
about to retrieve data
Back from mongoDB.find()
[{"_id":"5f403f7e5036d7bdb0adcd09","masterLanguage":"en-US","masterPhrase":"Customers","localizedLanguage":"es-MX","localizedPhrase":"Clientes"},{ etc...
【问题讨论】:
-
在您的代码中,
getLanguageTranslationData不返回任何内容,因此.then立即执行,arrayResult === undefined。有很多方法可以重构您的代码以使其工作,但我想最简单的方法就是放弃getLanguageTranslationData并将其代码移回app.get,除非您在其他地方需要它 - 在这种情况下您应该考虑调用mongoClient.connect()在getLanguageTranslationData之外,所以你可以将后者设为return dbo.collection(collectionName).find(query).toArray()。 -
谢谢。那么“返回结果”算不算返回呢?我试图减少嵌套代码的数量并追踪右括号/括号错误。最终,它可能是另一个模块中的数据访问层。
-
这可能是我想要做的。它使用回调。我会试试看:stackoverflow.com/questions/35246713/…
标签: javascript node.js async-await