MongoClient GetData例程的NodeJS ASync调用 [英] NodeJS ASync call of MongoClient GetData routine

查看:66
本文介绍了MongoClient GetData例程的NodeJS ASync调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码混合了 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可以避免这些问题.

When you look at the console.log below the code, things seem to be running out of order. I thought by making the function async and using the .then I would avoid those issues.

我希望MongoDB数据检索功能与app.get函数分开.没有数据返回到获取请求.我猜在函数返回值之前,app.get代码一直贯穿并结束.我需要纠正什么?

I want the MongoDB data retrieval function separate from the app.get function. No data is being returned to the get request. I guess the app.get code is falling through and ending before the function returns the value. What do I need to correct?

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控制台输出:

Node.JS Console output:

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 应该返回一个 promise ,以便您可以将其用作承诺处理程序,但对于您而言,对 getLanguageTranslationData 的调用将返回undefined,因为由于nodejs non-blocking ,此函数内的所有代码将异步执行自然.

The thing is getLanguageTranslationData should return a promise so that you can use it as a promise in your handler, but in your case, call to getLanguageTranslationData will return undefined as all the code inside this function will execute asynchronously due to nodejs non-blocking nature.

因此,您可以做的是从这样的 getLanguageTranslationData 函数返回promise.

So what you can do is return promise from your getLanguageTranslationData function like this.

function getLanguageTranslationData(fromLanguage, toLanguage) {
    const databaseUrl = "mongodb://localhost:27017"
    const databaseName = 'MyCompanyPOC'
    
    return new Promise((resolve, reject)=>{
        mongoClient.connect(databaseUrl, function(err, conn) {
            if (err) reject(err); 
            else{
                const collectionName = "Phrases";
                var dbo = conn.db(databaseName)
                var query = 
                        { $and: 
                               [ {masterLanguage: fromLanguage},
                                 {localizedLanguage: toLanguage} 
                               ]
                        }
                dbo.collection(collectionName).find(query).toArray( 
                     function(err, result) {
                          if (err) reject(err); 
                          else
                          resolve(result);    
                   }) 
            }
           
        }) 
    }) 
}

,然后在处理程序中使用await来使用返回的诺言

and then use await in your handler to use that promise returned

app.get("/api/gettranslations/:fromLanguage/:toLanguage", 
  async function(req, res) {
      try{
        let arrayResult = await getLanguageTranslationData(req.params.fromLanguage, req.params.toLanguage);
        res.status(200).json(arrayResult)
      }catch(err){
        // return error
      }
}) 

以上代码将为您提供所需要做的要点,实际代码可能会根据您的需要而变化.

The above code will give you the gist of what you need to do, actual code may vary according to your needs.

您可以从async-await "nofollow noreferrer>此处

You can refer async-await from here

这篇关于MongoClient GetData例程的NodeJS ASync调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆