javascript - 从 Mongo DB 获取数组。未处理的承诺拒绝
问题描述
我正在努力解决一个旨在从 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.
为了解决这个问题,任何人都可以看到我在函数中没有做对的事情吗?
解决方案
用 promise 包装函数内容:
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))