我对Promise
和async/await
都是陌生的。我有以下代码构成猫鼬查询:
// Bluebird's promise
const Prom = require('bluebird');
let formSampleQuery = (customerQuery) => {
return Prom.try(() => {
customerQuery.where("age").lt("30");
console.log("Formed Customer Query Object:\n", customerQuery);
return Prom.resolve(customerQuery);
})
}
然后我有以下使用async/await
调用此方法的方法:
let Customer = require('./src/models/customer.model');
exports.executeQuery = () => {
return Prom.try(async () => {
let customerQuery = Customer.find().lean();
customerQuery = await formSampleQuery(customerQuery);
console.log('Customer Query at Execute Query:\n', customerQuery) // Output coming undefined at this point
customerQuery.exec().then(res => {console.log(res)}); // At this point I get "TypeError: Cannot read property 'exec' of undefined"
});
}
我在customerQuery
方法中获得了完整的formSampleQuery
对象,但是当同一事物返回到executeQuery
方法时,它变得不确定,并且出现了这个错误:
TypeError:无法读取未定义的属性“ exec”
我要去哪里错了?
编辑1:
紧随其后的formCustomerQuery
查询对象的输出。
Query {
_mongooseOptions: { lean: true },
_transforms: [],
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts:
{ bufferCommands: true,
capped: false,
'$wasForceClosed': undefined },
name: 'customers',
collectionName: 'customers',
.........................
..........................
........................
_traceFunction: undefined,
'$useProjection': true }
我知道这时查询对象具有我指定的条件。它显示在日志中