最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

从Mongo数据库获取数组。 UnhandledPromiseRejection

网站源码admin17浏览0评论

从Mongo数据库获取数组。 UnhandledPromiseRejection

从Mongo数据库获取数组。 UnhandledPromiseRejection

我正在努力使用一个函数,该函数旨在从Mongo数据库(在Node JS中)提取数组并返回它。尽管这个想法很简单,并且我已经多次编写了这种代码。我缺少一些东西。

这里是该功能的代码:

function getDBArray(reqID) {
  MongoClient.connect(databaseUri, {useUnifiedTopology: true}, function (err, client) {
    if (err) {
      console.log('getDBArray: Error = ' + err)
      throw err
    }

    const db = client.db()
    let srchQuery = {}
    srchQuery['fieldID'] = reqID
    db.collection('theList', async function (err, collection) {
      try {
        await collection.find(srchQuery, {'target': true}).toArray(function (err, items) {
          if (err) throw err

          const resultArray = items;
          client.close();

          return resultArray;
        })
      }
      catch (error) {
        console.log('-catch (getDBArray)- ::>> ' + error)
      }
    })
  });
} /* End of getDBArray */

这是呼叫代码:

let myArray = getDBArray(dataID)
myArray.forEach(element => {
  console.log('myArray:'+element)
});

这就是我不断获得的日志:

...+00:00 app[web.1]: (node:23) UnhandledPromiseRejectionWarning: TypeError: Cannot read property   'forEach' of undefined
...+00:00 app[web.1]: at .... (/app/server.js:55:21)
...+00:00 app[web.1]: at ....
......
...+00:00 app[web.1]: (node:23) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch(). 
To terminate the node process on unhandled promise rejection, use the CLI flag...
...+00:00 app[web.1]: (node:23) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled will terminate
the Node.js process with a non-zero exit code.

有人能看到我在功能中做的不正确的事情来解决此问题吗?

回答如下:

包装带有诺言的函数:

function getDBArray(reqID) {
    return new Promise((resolve, reject) => {
        MongoClient.connect(databaseUri, {
            useUnifiedTopology: true
        }, function(err, client) {
            if (err) {
                console.log('getDBArray: Error = ' + err)
                reject(err)
            }

            const db = client.db()
            let srchQuery = {}
            srchQuery['fieldID'] = reqID
            db.collection('theList', async function(err, collection) {
                try {
                    await collection.find(srchQuery, {
                        'target': true
                    }).toArray(function(err, items) {
                        if (err) reject(err)

                        const resultArray = items;
                        client.close();

                        resolve(resultArray);
                    })
                } catch (error) {
                    reject(err)
                }
            })
        });
    })
}

然后致电:

getDBArray(dataID).then((myArray) => {
    myArray.forEach(element => {
        console.log('myArray:' + element)
    });
}).catch(e => console.log(e))

发布评论

评论列表(0)

  1. 暂无评论