假设我有一个函数,在该函数中我正在访问一个我无法更改的接口(interface)(在本例中为 Mongoose )。接口(interface)返回一个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
}
但此时我对代码不再满意,因为;
- 我必须声明一个函数文字,并且正在通往回调 hell 的路上。
- 我纯粹使用
call
,所以我仍然可以在函数中使用this
,但实际上到这里为止,我也可以传入response
作为第三个参数。
我确信一定有一种模式或某种东西可以以更简洁的方式处理这个问题,而不必声明新的函数文字。有人可以建议一个模式吗?有没有更简洁的方法来处理这种情况?
最佳答案
您可以根据需要向 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
关于javascript - 用于使用 Promise 处理外部接口(interface)中的参数的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36497056/