【发布时间】:2019-12-24 20:55:57
【问题描述】:
我有一个猫鼬模型,我在其中声明了 1 个应该返回所有功能的静态变量。
const Feature = require('./featureModel')
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schemaOptions = {
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
};
const ModemSchema = new Schema({
proxy_type: {
type: String,
default: 'None'
},
data_prioritization: {
type: String,
default: 'None'
}
}, schemaOptions);
ModemSchema.statics.possibleProxyTypes = async function () {
features = await Feature.find({})
return features
}
module.exports = mongoose.model('Modem', ModemSchema);
Modem.possibleProxyTypes我这样称呼它(类方法)
但是 await 没有等待,我得到了输出 [AsyncFunction] 。不知道这里出了什么问题。
【问题讨论】:
-
您可能忘记了括号吗?
Modem.possibleProxyTypes() -
Promise { <pending> }这是我打电话给Modem.possibleProxyTypes()@AsafAviv 时得到的结果 -
是的,
async函数总是返回一个承诺,即使你在被调用的函数中为它await,你也必须在承诺上调用.then()或await -
但是 mongoose 查询也返回 promise,这就是我添加 async 和 await 的原因。我在我的控制器中使用相同类型的代码,它在那里工作,但不是在这里@AsafAviv
-
你实际上甚至不需要
async,只需要return Feature.find({})。但在这种情况下没关系,在你的控制器中包含代码
标签: node.js mongoose async-await