javascript - 用于使用 Promise 处理外部接口(interface)中的参数的设计模式

标签 javascript node.js design-patterns

假设我有一个函数,在该函数中我正在访问一个我无法更改的接口(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

这称为部分应用:
https://en.wikipedia.org/wiki/Partial_application

关于javascript - 用于使用 Promise 处理外部接口(interface)中的参数的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36497056/

相关文章:

C++:路由到成员函数的静态函数包装器?

java - 如何在 PageObjects 模式中使用 WebDriver/Selenium 2 LoadComponents?

c# - Web 应用程序中的单例模式

javascript - 如何将对象序列化为 URL 查询参数列表?

javascript - 如何在提交表单后隐藏 Div 元素

javascript - 更改选中的 href 属性

jquery - ID 的 req.body 始终未定义,但我的客户端通过 jQuery .click() 调用获取正确的值

node.js - gulp.dest() 忽略子目录

javascript - Heroku Node 应用推送失败

node.js - Cloud Functions 何时重试?