我正在尝试从mongoDB读取数据。最终,我希望从数据库中检索到的数据是json格式的。我目前的功能是:
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true })
const getdata = async (): Promise<string[]> => {
let alldata: string[]
try {
await client.connect()
const database = client.db('data')
const collection = database.collection('datacollection')
const cursor = collection.find({ type: 'featureName' })
alldata = await cursor.toArray()
//console.log(alldata) //This correctly sends the required data to the console.
} finally {
void client.close()
}
//console.log(alldata) //This correctly sends the required data to the console.
return alldata
}
const data = getdata()
console.log(data) // this sends a "Promise { pending }"
我是javascript/typescript的新手,但我认为我用asyc函数和wait的->但事实显然并非如此。任何关于我做错了什么的建议都将不胜感激。
函数返回Promise
,因此需要使用promise.then
。
例如
getData().then((data) => {
console.log(data);
});
请查看此处的Promise文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise