Below piece of code does not wait for the database query to finish before print out the console.log and I have no idea why. It is confirmed that data exists.
const document = await this.database.find({ id: payload.user.id }).sort({ postedAt: 1 }).limit(1).exec((error: any, document: any) => {
(error) ? error : document;
});
console.log('Document: ', document);
Thank you!
This seems to work. Is there a way to make it cleaner? Thanks:
const document = () => new Promise((resolve: any, reject: any) => {
this.database.find({ id: payload.user.id }).sort({ postedAt: 1 }).limit(1).exec((error: any, document: any) => {
(error) ? reject(error) : resolve(document);
});
})
const x = await document().then((results: any) => {
console.log('Results: ', results);
return results;
}).catch((error: any) => {
console.log('Error: ', error);
return false;
});
console.log('Doc: ', x);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.