【发布时间】:2021-10-10 01:30:49
【问题描述】:
我正在学习 JS。我正在使用 Mongoose,我想将函数和参数传递给回调,但我必须改用 call()。
// Car is a model. Using Express in Node.js
express.Router().route('/')
.get((req,res,next)=>{
print(res,next,Cars.find)
})
const print = async(res,next,func,param1={})=>{
try {
const cars = await func.call(Cars,param1)
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(cars);
} catch (err)
next(err);
}
当我在 print(...) 中简单地执行 func(param1) 时,它对我不起作用,它会返回此错误。
MongooseError: `Model.find()` cannot run without a model as `this`.
Make sure you are calling `MyModel.find()` where `MyModel` is a Mongoose model.
您能否解释一下为什么会这样以及何时需要使用 apply()/call() 来传递它?在猫鼬的这种情况下和一般情况下?
我对 next() 和 next(err) 也有点困惑。文档说这只是为了让程序可以在某种意义上“跳过”错误,我可以明显地看到这一点。但它是像我们可以修改的回调函数还是内置的?
编辑:我在看How to access the correct `this` inside a callback,是不是因为不知何故该对象没有传递到print()?
【问题讨论】:
-
那行不通。
func_param1 = {}不可迭代 -
@CertainPerformance 哦,我看到我在开发代码中使用了 call() 而不是 apply()。但是 apply() 或 call() 的语法不是我要问的。我将其更改为 call()。谢谢。
-
您不应该在这里使用
call- 现在您的print函数仅适用于Cars模型。相反,使用简单的await func();,但将Cars.find.bind(Cars, {})或() => Cars.find({})作为回调传递。 -
感谢@Bergi。因为对于不同的http请求我会使用不同的方法,所以我会在父函数
get()中调用Cars.find()。这种方式更容易调试。但这绝对是我工具箱中的一个工具。
标签: javascript this apply pass-by-reference next