如何将res.json作为回调函数传递?(How to pass res.json as a callback function?)

编程入门 行业动态 更新时间:2024-10-23 16:15:24
如何将res.json作为回调函数传递?(How to pass res.json as a callback function?)

我有一个带回调参数的函数。 我用这种方式,它工作得很好: DB.last(user,(data) => res.json(data)); 我尝试将其重写为类似的东西,使其更具可读性: DB.last(user,res.json);

DB.last在哪里

static last(user, callback) { let data = {name: user, registered: new Date()}; callback(data); }

函数调用DB.last当然是在快速路由器脚本中。

我想我看到了两者之间的区别,但是将res.json作为回调参数传递给我的DB模块似乎是合乎逻辑的(我的意思是我可以在JS中传递一个函数),但它不会以这种方式工作。

我错过了什么? 为什么这不起作用?

I have a function with a callback parameter. I use it this way, and it works just fine: DB.last(user,(data) => res.json(data)); I tried to rewrite it to something like this, to make it more readable: DB.last(user,res.json);

where DB.last is

static last(user, callback) { let data = {name: user, registered: new Date()}; callback(data); }

The function call DB.last is in an express router script of course.

I think I see the difference between the two but it seems logical to me to pass res.json to my DB module as a callback parameter (I mean I can pass a function in JS), but it won't work this way.

What am I missing? Why won't this work?

最满意答案

你必须使用res.json.bind(res) 。

当你调用res.json() ,它会在res对象上执行(即this值在执行函数时引用res )。 但是,当您将res.json作为回调参数传递,然后将其作为callback()调用时,它将在对象上执行,该对象在callback()的上下文中执行。

使用bind()方法强制在res上调用函数。 无论何时调用绑定函数,其值始终为res 。

You have to use res.json.bind(res).

When you call res.json(), it is executed on the res object (i.e. this value refers to res when the function is executed). However, when you pass res.json as a callback parameter, and then call it as callback(), it is executed on the object which is this in the context where callback() is called.

Using the bind() method forces the function to be called on res. Whenever you call the bound function, its this value will always be res.

更多推荐

本文发布于:2023-07-26 00:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268337.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   如何将   函数   res   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!