-
I have the following Model: const userSchema = new mongoose.Schema({
// long long schema... etc
age: Number,
})
const UserModel = mongoose.model('User', userSchema, 'users') I have the following function: async function x(y) {
// @param y: function | asyncfunction
const YreturnValue = await y()
YreturnValue.sort('age')
return YreturnValue // returns a Mongoose Query
} and I have the following route: router.route('/').get(async (req, res, next) => {
const query = await x(() => UserModel.find({}))
const docs = await query
res.status(200).json({ data: docs })
}) When I request the I am awaiting the function x because it's an async function (i.e, it returns a Promise), and the resolved value of the function x is expected to be a mongoose Query object.
What's the problem? I have asked this question on StackOverflow, but I didn't get any fulfilling response. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I think that the problem comes because you are awaiting the // @param y: function | asyncfunction
function x(y) {
return new Promise((resolve, reject) => {
y.sort('age').exec((err, results) => {
if(err){
reject(err);
}else{
resolve(results);
}
});
});
} In your version: async function x(y) {
// @param y: function | asyncfunction
const YreturnValue = await y()
YreturnValue.sort('age')
return YreturnValue // returns a Mongoose Query
} When you You maybe could try this version that I'm not sure if it would work: // @param y: function | asyncfunction
async function x(y) {
sortedQuery = y.sort('age');
const YreturnValue = await sortedQuery();
return YreturnValue // returns an Array
} If what you want is to return a Query instance with the sort configuration, then you could try: // @param y: function | asyncfunction
async function x(y) {
sortedQuery = y.sort('age');
return sortedQuery;
} And then here: router.route('/').get(async (req, res, next) => {
const query = await x(() => UserModel.find({}))
const docs = await query
res.status(200).json({ data: docs })
})
|
Beta Was this translation helpful? Give feedback.
-
If you You would have to wrap your query in an object, like: async function x(y) {
// @param y: function | asyncfunction
const YreturnValue = await y()
YreturnValue.sort('age')
return { query: YreturnValue } // returns a Mongoose Query
} |
Beta Was this translation helpful? Give feedback.
If you
return
something that has athen()
function from an async function, JavaScript will automatically callthen()
. There's no way to return a thenable from an async function.You would have to wrap your query in an object, like: