用于处理带有promise的外部接口中的参数的设计模式
Design Pattern for handling arguments in external interfaces with promises
假设我有一个函数,在其中我访问一个无法更改的接口(在本例中为mongoose)。该接口返回一个promise,该promise只是传入找到的资源;
show = function(response) {
Resource.findById(req.params.id).then(renderResource);
}
function renderResource(resource) {
// render the response
}
为了呈现响应,我需要访问show
函数中的response
参数。我可以使用bind
函数,劫持this
作为响应变量;
show = function(response) {
Resource.findById(req.params.id).then(renderResource.bind(response));
}
function renderResource(resource) {
this.send(resource);
}
但是,如果我想将另一个参数传递到renderResource
函数中,该怎么办?我唯一能做到的就是这样;
show = function(response) {
Resource.findById(req.params.id).then(function(resource) {
renderResource.call(response, resource, "foo"));
}
}
function renderResource(resource, otherArg) {
this.send(resource);
//do something with otherArg
}
但在这一点上,我不再对代码感到满意,因为;
- 我不得不声明一个函数文本,并且正在回调地狱
- 我纯粹使用
call
,所以我仍然可以在函数中使用this
,但实际上,到目前为止,我还不如将response
作为第三个arg传入
我确信,必须有一种模式或某种东西来以更整洁的方式处理这个问题,而不必声明新的函数文本。有人能提出一个模式吗?有没有一种更整洁的方法来处理这种情况?
您可以根据需要向bind
传递任意多个参数。我会避免使用this
作为传递参数的方式,以避免混淆。
show = function(response) {
Resource.findById(req.params.id)
.then(renderResource.bind(null, response, "foo"));
}
function renderResource(response, otherArg, resource) {
response.send(resource);
//do something with otherArg
}
有关详细信息,请参阅bind
文档:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
这被称为特殊应用程序:
https://en.wikipedia.org/wiki/Partial_application
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 使用Express捕获参数
- 参数变量出现ngTable指令问题
- AngularJS:我可以跳过函数参数回调吗
- 如何使用skip参数使用angular ui引导进行服务器端分页
- 要求未定义JS回调参数
- 我的jQuery插件参数没有正确启动,遇到了问题
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- jquery设置为使用参数运行
- Javascript”;类“;带有参数的扩展
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 如何使用外部接口将参数从 JavaScript 传递到 AS3
- 用于处理带有promise的外部接口中的参数的设计模式
- 获取用于接口目的的函数参数名称
- 如何对类的构造函数参数的流类型接口进行严格的类型检查?
- 类型错误:参数1的窗口.getDefaultComputedStyle不实现接口元素
- Node的参数1.appendChild没有实现接口Node.同时追加到新元素
- 节点的参数1.appendChild没有实现接口Node
- 将接口文字传递给函数参数
- TypeError:Node.appendChild的参数1未实现接口Node